<commit_before>/**
 * Module dependencies.
 */
var express = require('express');
var cookieParser = require('cookie-parser');
var compress = require('compression');
var favicon = require('serve-favicon');
var session = require('express-session');
var bodyParser = require('body-parser');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var lusca = require('lusca');
var methodOverride = require('method-override');
var dotenv = require('dotenv');
var MongoStore = require('connect-mongo/es5')(session);
var flash = require('express-flash');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var expressValidator = require('express-validator');
var sass = require('node-sass-middleware');
var _ = require('lodash');

/**
 * Load environment variables from .env file, where API keys and passwords are configured.
 *
 * Default path: .env (You can remove the path argument entirely, after renaming `.env.example` to `.env`)
 */
dotenv.load();

/**
 * Controllers (route handlers).
 */
var homeController = require('./controllers/home');
var userController = require('./controllers/user');
var apiController = require('./controllers/api');
var contactController = require('./controllers/contact');

/**
 * API keys and Passport configuration.
 */
var passportConf = require('./config/passport');

/**
 * Create Express server.
 */
var app = express();

/**
 * Connect to MongoDB.
 */
mongoose.connect(process.env.MONGODB || process.env.MONGOLAB_URI);
mongoose.connection.on('error', function() {
  console.log('MongoDB Connection Error. Please make sure that MongoDB is running.');
  process.exit(1);
});

/**
 * Express configuration.
 */
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(compress());
app.use(sass({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  sourceMap: true
}));
app.use(logger('dev'));
app.use(favicon(path.join(__dirname, 'public', 'favicon.png')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: process.env.SESSION_SECRET,
  store: new MongoStore({
    url: process.env.MONGODB || process.env.MONGOLAB_URI,
    autoReconnect: true
  })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(lusca({
  csrf: true,
  xframe: 'SAMEORIGIN',
  xssProtection: true
}));
app.use(function(req, res, next) {
  res.locals.user = req.user;
  next();
});
app.use(function(req, res, next) {
  if (/api/i.test(req.path)) {
    req.session.returnTo = req.path;
  }
  next();
});
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));

/**
 * Primary app routes.
 */
app.get('/', homeController.index);
app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);
app.get('/logout', userController.logout);
app.get('/forgot', userController.getForgot);
app.post('/forgot', userController.postForgot);
app.get('/reset/:token', userController.getReset);
app.post('/reset/:token', userController.postReset);
app.get('/signup', userController.getSignup);
app.post('/signup', userController.postSignup);
app.get('/contact', contactController.getContact);
app.post('/contact', contactController.postContact);
app.get('/account', passportConf.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConf.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConf.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConf.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConf.isAuthenticated, userController.getOauthUnlink);

/**
 * API examples routes.
 */
app.get('/api', apiController.getApi);
app.get('/api/lastfm', apiController.getLastfm);
app.get('/api/nyt', apiController.getNewYorkTimes);
app.get('/api/aviary', apiController.getAviary);
app.get('/api/steam', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getSteam);
app.get('/api/stripe', apiController.getStripe);
app.post('/api/stripe', apiController.postStripe);
app.get('/api/scraping', apiController.getScraping);
app.get('/api/twilio', apiController.getTwilio);
app.post('/api/twilio', apiController.postTwilio);
app.get('/api/clockwork', apiController.getClockwork);
app.post('/api/clockwork', apiController.postClockwork);
app.get('/api/foursquare', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFoursquare);
app.get('/api/tumblr', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTumblr);
app.get('/api/facebook', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFacebook);
app.get('/api/github', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getGithub);
app.get('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTwitter);
app.post('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.postTwitter);
app.get('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getVenmo);
app.post('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.postVenmo);
app.get('/api/linkedin', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getLinkedin);
app.get('/api/instagram', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getInstagram);
app.get('/api/yahoo', apiController.getYahoo);
app.get('/api/paypal', apiController.getPayPal);
app.get('/api/paypal/success', apiController.getPayPalSuccess);
app.get('/api/paypal/cancel', apiController.getPayPalCancel);
app.get('/api/lob', apiController.getLob);
app.get('/api/bitgo', apiController.getBitGo);
app.post('/api/bitgo', apiController.postBitGo);

/**
 * OAuth authentication routes. (Sign in)
 */
app.get('/auth/instagram', passport.authenticate('instagram'));
app.get('/auth/instagram/callback', passport.authenticate('instagram', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'] }));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' }));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/linkedin', passport.authenticate('linkedin', { state: 'SOME STATE' }));
app.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});

/**
 * OAuth authorization routes. (API examples)
 */
app.get('/auth/foursquare', passport.authorize('foursquare'));
app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/foursquare');
});
app.get('/auth/tumblr', passport.authorize('tumblr'));
app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/tumblr');
});
app.get('/auth/venmo', passport.authorize('venmo', { scope: 'make_payments access_profile access_balance access_email access_phone' }));
app.get('/auth/venmo/callback', passport.authorize('venmo', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/venmo');
});
app.get('/auth/steam', passport.authorize('openid', { state: 'SOME STATE' }));
app.get('/auth/steam/callback', passport.authorize('openid', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});

/**
 * Error Handler.
 */
app.use(errorHandler());

/**
 * Start Express server.
 */
app.listen(app.get('port'), function() {
  console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
});

module.exports = app;
<commit_msg>first fix<commit_after>/**
 * Module dependencies.
 */
var express = require('express');
var cookieParser = require('cookie-parser');
var compress = require('compression');
var favicon = require('serve-favicon');
var session = require('express-session');
var bodyParser = require('body-parser');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var lusca = require('lusca');
var methodOverride = require('method-override');
var dotenv = require('dotenv');
var MongoStore = require('connect-mongo/es5')(session);
var flash = require('express-flash');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var expressValidator = require('express-validator');
var sass = require('node-sass-middleware');
var _ = require('lodash');

/**
 * Load environment variables from .env file, where API keys and passwords are configured.
 *
 * Default path: .env (You can remove the path argument entirely, after renaming `.env.example` to `.env`)
 */
dotenv.load();

/**
 * Controllers (route handlers).
 */
var homeController = require('./controllers/home');
var userController = require('./controllers/user');
var apiController = require('./controllers/api');
var contactController = require('./controllers/contact');

/**
 * API keys and Passport configuration.
 */
var passportConf = require('./config/passport');

/**
 * Create Express server.
 */
var app = express();

/**
 * Connect to MongoDB.
 */
mongoose.connect(process.env.MONGODB || process.env.MONGOLAB_URI);
mongoose.connection.on('error', function() {
  console.log('MongoDB Connection Error. Please make sure that MongoDB is running.');
  process.exit(1);
});

/**
 * Express configuration.
 */
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(compress());
app.use(sass({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  sourceMap: true
}));
app.use(logger('dev'));
app.use(favicon(path.join(__dirname, 'public', 'favicon.png')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: process.env.SESSION_SECRET,
  store: new MongoStore({
    url: process.env.MONGODB || process.env.MONGOLAB_URI,
    autoReconnect: true
  })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(lusca({
  csrf: true,
  xframe: 'SAMEORIGIN',
  xssProtection: true
}));
app.use(function(req, res, next) {
  res.locals.user = req.user;
  next();
});
app.use(function(req, res, next) {
  if (/api/i.test(req.path)) {
    req.session.returnTo = req.path;
  }
  next();
});
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));

/**
 * Primary app routes.
 */
app.get('/', homeController.index);
app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);
app.get('/logout', userController.logout);
app.get('/forgot', userController.getForgot);
app.post('/forgot', userController.postForgot);
app.get('/reset/:token', userController.getReset);
app.post('/reset/:token', userController.postReset);
app.get('/signup', userController.getSignup);
app.post('/signup', userController.postSignup);
app.get('/contact', contactController.getContact);
app.post('/contact', contactController.postContact);
app.get('/account', passportConf.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConf.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConf.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConf.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConf.isAuthenticated, userController.getOauthUnlink);

/**
 * API examples routes.
 */
app.get('/api', apiController.getApi);
app.get('/api/lastfm', apiController.getLastfm);
app.get('/api/nyt', apiController.getNewYorkTimes);
app.get('/api/aviary', apiController.getAviary);
app.get('/api/steam', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getSteam);
app.get('/api/stripe', apiController.getStripe);
app.post('/api/stripe', apiController.postStripe);
app.get('/api/scraping', apiController.getScraping);
app.get('/api/twilio', apiController.getTwilio);
app.post('/api/twilio', apiController.postTwilio);
app.get('/api/clockwork', apiController.getClockwork);
app.post('/api/clockwork', apiController.postClockwork);
app.get('/api/foursquare', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFoursquare);
app.get('/api/tumblr', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTumblr);
app.get('/api/facebook', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFacebook);
app.get('/api/github', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getGithub);
app.get('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTwitter);
app.post('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.postTwitter);
app.get('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getVenmo);
app.post('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.postVenmo);
app.get('/api/linkedin', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getLinkedin);
app.get('/api/instagram', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getInstagram);
app.get('/api/yahoo', apiController.getYahoo);
app.get('/api/paypal', apiController.getPayPal);
app.get('/api/paypal/success', apiController.getPayPalSuccess);
app.get('/api/paypal/cancel', apiController.getPayPalCancel);
app.get('/api/lob', apiController.getLob);
app.get('/api/bitgo', apiController.getBitGo);
app.post('/api/bitgo', apiController.postBitGo);

/**
 * OAuth authentication routes. (Sign in)
 */
app.get('/auth/instagram', passport.authenticate('instagram'));
app.get('/auth/instagram/callback', passport.authenticate('instagram', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'] }));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' }));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/linkedin', passport.authenticate('linkedin', { state: 'SOME STATE' }));
app.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});

/**
 * OAuth authorization routes. (API examples)
 */
app.get('/auth/foursquare', passport.authorize('foursquare'));
app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/foursquare');
});
app.get('/auth/tumblr', passport.authorize('tumblr'));
app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/tumblr');
});
app.get('/auth/venmo', passport.authorize('venmo', { scope: 'make_payments access_profile access_balance access_email access_phone' }));
app.get('/auth/venmo/callback', passport.authorize('venmo', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/venmo');
});
app.get('/auth/steam', passport.authorize('openid', { state: 'SOME STATE' }));
app.get('/auth/steam/callback', passport.authorize('openid', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});

/**
 * Error Handler.
 */

app.use(errorHandler());

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

module.exports = app;
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var sets = require('simplesets');

app.use(express.static('static'));
app.set('view engine', 'jade');

var names = [];

// Initialize whitelist and black list
var white_list = new sets.Set();
load_file(white_list, 'special_names/whitelist.txt');
var black_list = new sets.Set();
load_file(black_list, 'special_names/blacklist.txt');

function load_file(s, file) {
  fs.readFile(file, 'utf8', function(err, data) {
    if (err) {
      return console.log(err);
    }
    t = data.split("\n");
    for (var i = 0; i < t.length; i++) {
      s.add(t[i].toLowerCase());
    }
    console.log("Finished loading " + file);
  });
};

app.get('/', function (req, res){
  res.render('index');
});

app.get('/tree', function (req, res){
  res.render('tree', {names: names});
});

app.get('/moderator', function (req, res){
  res.render('moderator', {names: names});
});

io.on('connection', function(socket){
  console.log('A user connected from: ' + socket.handshake.address);
  socket.on('add name', function(msg){
    console.log('Attempting to add name ' + msg);
    if (black_list.has(msg.toLowerCase())) {
       // TODO: Warn client
       console.log(socket.handshake.address + " entered a bad name");
       return "Bad name";
    }
    // TODO: White list
    names.push(msg);
    io.emit('add name', msg)
  });
});

http.listen(3000, function(){
  console.log('Listening on port 3000!');
});
<commit_msg>Fix the Set Formatting<commit_after>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var sets = require('simplesets');

app.use(express.static('static'));
app.set('view engine', 'jade');

var names = [];

// Initialize whitelist and black list
var white_list = new sets.Set();
load_file(white_list, 'special_names/whitelist.txt');
var black_list = new sets.Set();
load_file(black_list, 'special_names/blacklist.txt');

function load_file(s, file) {
  fs.readFile(file, 'utf8', function(err, data) {
    if (err) {
      return console.log(err);
    }

    t = data.split("\r\n");
    for (var i = 0; i < t.length; i++) {
      s.add(t[i].toLowerCase());
    }
    console.log("Finished loading " + file);
  });
};

app.get('/', function (req, res){
  res.render('index');
});

app.get('/tree', function (req, res){
  res.render('tree', {names: names});
});

app.get('/moderator', function (req, res){
  res.render('moderator', {names: names});
});

io.on('connection', function(socket){
  console.log('A user connected from: ' + socket.handshake.address);
  socket.on('add name', function(msg){
    console.log('Attempting to add name ' + msg);
    if (black_list.has(msg.toLowerCase())) {
       // TODO: Warn client
       console.log(socket.handshake.address + " entered a bad name");
       return "Bad name";
    }
    // TODO: White list
    names.push(msg);
    io.emit('add name', msg)
  });
});

http.listen(3000, function(){
  console.log('Listening on port 3000!');
});
<|endoftext|>


<commit_before>var express = require('express'),
    routes = require('./routes'),
    path = require('path'),
    config = require('./config'),
    async = require('async'),
    gpio = require('rpi-gpio'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

// persistant variables
var gpio_state = new Array();
var status = 'BTWN';

app.configure(function(){
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.favicon());
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));
});

server.listen(app.get('port'))
console.log("Listening on port " + app.get('port'));

app.get('/', routes.index);

function delayPinWrite(pin, value, callback) {
    setTimeout(function() {
        gpio.write(pin, value, callback);
    }, config.RELAY_TIMEOUT);
}

// code below to listen for changes to gpio
gpio.on('change', function(channel, value) {
    //console.log("GPIO STATUS C: " + channel + " V: " + value);
    if (channel == config.GARAGE_DOWN) {
        if (value == true) status = 'DOWN';
        if (value == false) status = 'BTWN';
        io.sockets.emit('ginfo', status);
        io.sockets.emit('log', status);
        //console.log("GARAGE_GPIO " + status);
    }
    if (channel == config.GARAGE_UP) {
        if (value == true) status = 'UP';
        if (value == false) status = 'BTWN';
        io.sockets.emit('ginfo', status);
        io.sockets.emit('log', status);
        //console.log("GARAGE_GPIO " + status);
    }
});

// config up down monitor pins to report status
gpio.setup(config.GARAGE_DOWN, gpio.DIR_IN);
gpio.setup(config.GARAGE_UP, gpio.DIR_IN);
gpio.setup(config.GARAGE_PIN, gpio.DIR_OUT);

io.sockets.on('connection', function (socket) {
    var connectAddr = socket.handshake.address;
    console.log("New connection from " + connectAddr.address + ":" + connectAddr.port);

    // connected
    socket.emit('cok', 'Connected');

    // client requesting status
    socket.on('status', function (data) {
        console.log('Status requested: ' + data);
        socket.emit('ginfo', status);
    });

    // garage move
    socket.on('move', function (data) {
        console.log('Requesting garage movement, data: ' + data);

        async.series([
            function(callback) {
                gpio.write(config.GARAGE_PIN, config.RELAY_ON, function(err) {
                    if (err) throw err;
                });
                callback();
            },
            function(callback) {
                delayPinWrite(config.GARAGE_PIN, config.RELAY_OFF, callback);
            }
        ]);

        socket.emit('log', 'Garage moved');
    });
});

function gpio_read_state_pin(pin) {
    gpio.read(pin, function(err, value) {
        if (err){
            console.log("ERR: " + err);
        } else {
            cur_state = gpio_state[pin];
            if(cur_state !== value) {
                console.log("p: " + pin + "c: " + cur_state + "v: " + value);
                var prev_state = cur_state;
                gpio_state[pin] = value;
                gpio.emit('change', pin, value);
            }
        }
    });
}

setInterval(function(){
    gpio_read_state_pin(config.GARAGE_DOWN);
    gpio_read_state_pin(config.GARAGE_UP);
}, 200); // check state every 200ms
<commit_msg>debug logging change for gpio<commit_after>var express = require('express'),
    routes = require('./routes'),
    path = require('path'),
    config = require('./config'),
    async = require('async'),
    gpio = require('rpi-gpio'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

// persistant variables
var gpio_state = new Array();
var status = 'BTWN';

app.configure(function(){
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.favicon());
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));
});

server.listen(app.get('port'))
console.log("Listening on port " + app.get('port'));

app.get('/', routes.index);

function delayPinWrite(pin, value, callback) {
    setTimeout(function() {
        gpio.write(pin, value, callback);
    }, config.RELAY_TIMEOUT);
}

// code below to listen for changes to gpio
gpio.on('change', function(channel, value) {
    //console.log("GPIO STATUS C: " + channel + " V: " + value);
    if (channel == config.GARAGE_DOWN) {
        if (value == true) status = 'DOWN';
        if (value == false) status = 'BTWN';
        io.sockets.emit('ginfo', status);
        io.sockets.emit('log', status);
        //console.log("GARAGE_GPIO " + status);
    }
    if (channel == config.GARAGE_UP) {
        if (value == true) status = 'UP';
        if (value == false) status = 'BTWN';
        io.sockets.emit('ginfo', status);
        io.sockets.emit('log', status);
        //console.log("GARAGE_GPIO " + status);
    }
    console.log("GPIO Change, new status: " + status);
});

// config up down monitor pins to report status
gpio.setup(config.GARAGE_DOWN, gpio.DIR_IN);
gpio.setup(config.GARAGE_UP, gpio.DIR_IN);
gpio.setup(config.GARAGE_PIN, gpio.DIR_OUT);

io.sockets.on('connection', function (socket) {
    var connectAddr = socket.handshake.address;
    console.log("New connection from " + connectAddr.address + ":" + connectAddr.port);

    // connected
    socket.emit('cok', 'Connected');

    // client requesting status
    socket.on('status', function (data) {
        console.log('Status requested: ' + data);
        socket.emit('ginfo', status);
    });

    // garage move
    socket.on('move', function (data) {
        console.log('Requesting garage movement, data: ' + data);

        async.series([
            function(callback) {
                gpio.write(config.GARAGE_PIN, config.RELAY_ON, function(err) {
                    if (err) throw err;
                });
                callback();
            },
            function(callback) {
                delayPinWrite(config.GARAGE_PIN, config.RELAY_OFF, callback);
            }
        ]);

        socket.emit('log', 'Garage moved');
    });
});

function gpio_read_state_pin(pin) {
    gpio.read(pin, function(err, value) {
        if (err){
            console.log("ERR: " + err);
        } else {
            cur_state = gpio_state[pin];
            if(cur_state !== value) {
                console.log("p: " + pin + "c: " + cur_state + "v: " + value);
                var prev_state = cur_state;
                gpio_state[pin] = value;
                gpio.emit('change', pin, value);
            }
        }
    });
}

setInterval(function(){
    gpio_read_state_pin(config.GARAGE_DOWN);
    gpio_read_state_pin(config.GARAGE_UP);
}, 200); // check state every 200ms
<|endoftext|>


<commit_before>var express          = require('express'),
    compression      = require('compression'),
    expressValidator = require('express-validator'),
    path             = require('path'),
    fs               = require('fs');
    favicon          = require('serve-favicon'),
    logger           = require('morgan'),
    cookieParser     = require('cookie-parser'),
    bodyParser       = require('body-parser'),
    util             = require('util'),
    LRU              = require('lru-cache'),
    uuid             = require('uuid'),
    hljs             = require(path.join(__dirname,'node_modules','highlight.js','lib','index.js'));

var storage_type   = process.env.NODE_NOPASTE_STORAGE_TYPE   || 'memory';
var redis_hash_key = process.env.NODE_NOPASTE_REDIS_HASH_KEY || "node-nopaste-storage";
var lru_max_age    = process.env.NODE_NOPASTE_LRU_MAX_AGE    || 60 * 60 * 24;

var app = express();

var cache = LRU({ maxAge: lru_max_age });

var highlightjs_path    = path.join(__dirname,'node_modules','highlight.js','lib','highlight.js');
var highlightjs_css_dir = path.join(__dirname,'node_modules','highlight.js','styles');

var ghlightjs_css_files = {};
var ghlightjs_image_files = {};
fs.readdirSync(highlightjs_css_dir).filter(function(file){
    return /^.*\.(css|png|jpg)$/.test(file);
}).forEach(function(file){
    var match = file.match(/^(.+)\.(.+)$/);
    switch( match[2] ) {
        case "css":
            ghlightjs_css_files[match[1]] = file;
            break;
        case 'jpg':
            ghlightjs_image_files[file] = 'image/jpag';
            break;
        default:
            ghlightjs_image_files[file] = 'image/' + match[2];
            break;
    }
});

var storage = (function(){
    var Storage;
    if( storage_type == 'memory' ) {
        Storage = function(){
            this.data = {};
        };
        Storage.prototype.set = function(uuid,data) {
            this.data[uuid] = data;
        };
        Storage.prototype.get = function(uuid,callback) {
            callback(null,this.data[uuid]);
        };
        return new Storage();
    } else if( storage_type == 'redis'  ) {
        Storage = function(){
            var redis   = require("redis");
            this.client = redis.createClient();
            this.redis_hash_key = redis_hash_key;
        };
        Storage.prototype.set = function(uuid,data) {
            this.client.hset(this.redis_hash_key, uuid, data);
        };
        Storage.prototype.get = function(uuid,callback) {
            this.client.hget(this.redis_hash_key,uuid,callback);
        };
        return new Storage();
    }
}())

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(compression());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressValidator());

app.use(function (req, res, next) {
    res.locals = {
        title: 'No Paste',
        ghlightjs_css_files: ghlightjs_css_files
    };
    next();
});

app.get('/css/:style',function(req,res,next) {
    var style = req.params.style;

    var file;
    var content_type;
    if( ghlightjs_css_files[style]) {
        file         = ghlightjs_css_files[style];
        content_type = 'text/css';
    }
    else if ( ghlightjs_image_files[style] ) {
        file         = style;
        content_type = ghlightjs_image_files[style];
    }
    else {
        res.status(404).send('Unexpected style: ' + style);
        return;
    }

    res.append('Content-Type',content_type);
    res.sendFile(path.join(highlightjs_css_dir,file));
});

app.get('/', function(req, res, next) {
  res.render('index');
});

app.post('/add',function(req, res, next) {
    req.checkBody('data', 'Invalid data').notEmpty();

    var errors = req.validationErrors();
    if (errors) {
        res.status(400).send('There have been validation errors: ' + util.inspect(errors));
        return;
    }

    var uuid_v1 = uuid.v1();
    storage.set(uuid_v1,req.body['data']);

    res.redirect('/show?uuid=' + uuid_v1);
});

app.get('/show',function(req, res, next) {
    req.checkQuery('uuid', 'Invalid uuid').notEmpty();

    var errors = req.validationErrors();
    if (errors) {
        res.status(400).send('There have been validation errors: ' + util.inspect(errors));
        return;
    }

    var style   = req.cookies['style'] || 'default';

    // To turn off after installation version number for backwards compatibility.
    style = style.replace(/\.css/,'');

    var results = cache.get(req.query['uuid']);
    if( results ) {
        return res.render('show',
            { value: results['value'], language: results['language'] ,style: style });
    }

    storage.get(req.query['uuid'],function(err,data){
        if(err || !data) {
            res.status(400).send('Unexpected uuid: ' + (req.query['uuid'] || ''));
            return;
        }
        var results = hljs.highlightAuto(data);
        cache.set(req.query['uuid'],results);
        res.render('show', { value: results['value'], language: results['language'] ,style: style });
    });
});

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

if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>Fixed regular expression<commit_after>var express          = require('express'),
    compression      = require('compression'),
    expressValidator = require('express-validator'),
    path             = require('path'),
    fs               = require('fs');
    favicon          = require('serve-favicon'),
    logger           = require('morgan'),
    cookieParser     = require('cookie-parser'),
    bodyParser       = require('body-parser'),
    util             = require('util'),
    LRU              = require('lru-cache'),
    uuid             = require('uuid'),
    hljs             = require(path.join(__dirname,'node_modules','highlight.js','lib','index.js'));

var storage_type   = process.env.NODE_NOPASTE_STORAGE_TYPE   || 'memory';
var redis_hash_key = process.env.NODE_NOPASTE_REDIS_HASH_KEY || "node-nopaste-storage";
var lru_max_age    = process.env.NODE_NOPASTE_LRU_MAX_AGE    || 60 * 60 * 24;

var app = express();

var cache = LRU({ maxAge: lru_max_age });

var highlightjs_path    = path.join(__dirname,'node_modules','highlight.js','lib','highlight.js');
var highlightjs_css_dir = path.join(__dirname,'node_modules','highlight.js','styles');

var ghlightjs_css_files = {};
var ghlightjs_image_files = {};
fs.readdirSync(highlightjs_css_dir).filter(function(file){
    return /^.+\.(css|png|jpg)$/.test(file);
}).forEach(function(file){
    var match = file.match(/^(.+)\.(.+)$/);
    switch( match[2] ) {
        case "css":
            ghlightjs_css_files[match[1]] = file;
            break;
        case 'jpg':
            ghlightjs_image_files[file] = 'image/jpag';
            break;
        default:
            ghlightjs_image_files[file] = 'image/' + match[2];
            break;
    }
});

var storage = (function(){
    var Storage;
    if( storage_type == 'memory' ) {
        Storage = function(){
            this.data = {};
        };
        Storage.prototype.set = function(uuid,data) {
            this.data[uuid] = data;
        };
        Storage.prototype.get = function(uuid,callback) {
            callback(null,this.data[uuid]);
        };
        return new Storage();
    } else if( storage_type == 'redis'  ) {
        Storage = function(){
            var redis   = require("redis");
            this.client = redis.createClient();
            this.redis_hash_key = redis_hash_key;
        };
        Storage.prototype.set = function(uuid,data) {
            this.client.hset(this.redis_hash_key, uuid, data);
        };
        Storage.prototype.get = function(uuid,callback) {
            this.client.hget(this.redis_hash_key,uuid,callback);
        };
        return new Storage();
    }
}())

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(compression());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressValidator());

app.use(function (req, res, next) {
    res.locals = {
        title: 'No Paste',
        ghlightjs_css_files: ghlightjs_css_files
    };
    next();
});

app.get('/css/:style',function(req,res,next) {
    var style = req.params.style;

    var file;
    var content_type;
    if( ghlightjs_css_files[style]) {
        file         = ghlightjs_css_files[style];
        content_type = 'text/css';
    }
    else if ( ghlightjs_image_files[style] ) {
        file         = style;
        content_type = ghlightjs_image_files[style];
    }
    else {
        res.status(404).send('Unexpected style: ' + style);
        return;
    }

    res.append('Content-Type',content_type);
    res.sendFile(path.join(highlightjs_css_dir,file));
});

app.get('/', function(req, res, next) {
  res.render('index');
});

app.post('/add',function(req, res, next) {
    req.checkBody('data', 'Invalid data').notEmpty();

    var errors = req.validationErrors();
    if (errors) {
        res.status(400).send('There have been validation errors: ' + util.inspect(errors));
        return;
    }

    var uuid_v1 = uuid.v1();
    storage.set(uuid_v1,req.body['data']);

    res.redirect('/show?uuid=' + uuid_v1);
});

app.get('/show',function(req, res, next) {
    req.checkQuery('uuid', 'Invalid uuid').notEmpty();

    var errors = req.validationErrors();
    if (errors) {
        res.status(400).send('There have been validation errors: ' + util.inspect(errors));
        return;
    }

    var style   = req.cookies['style'] || 'default';

    // To turn off after installation version number for backwards compatibility.
    style = style.replace(/\.css/,'');

    var results = cache.get(req.query['uuid']);
    if( results ) {
        return res.render('show',
            { value: results['value'], language: results['language'] ,style: style });
    }

    storage.get(req.query['uuid'],function(err,data){
        if(err || !data) {
            res.status(400).send('Unexpected uuid: ' + (req.query['uuid'] || ''));
            return;
        }
        var results = hljs.highlightAuto(data);
        cache.set(req.query['uuid'],results);
        res.render('show', { value: results['value'], language: results['language'] ,style: style });
    });
});

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

if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<|endoftext|>


<commit_before>// Require the http module and the proxy module
var http      = require('http'),
    httpProxy = require('http-proxy'),
    url       = require('url');
    routes    = require('./config/routes');

console.log(routes);
// Create the proxy
var proxy = httpProxy.createProxyServer({});

// Setup the proxy server and determine routing
var server = http.createServer(function(req, res) {
  var rqstUrl = req.headers.host;
  console.log(rqstUrl);
  if(routes[rqstUrl]) {
    target_address = routes.ipaddress + routes[rqstUrl].target;
    proxy.web(req, res, { target: target_address });
  }
});

// Determine the port number
var defaultPort = 3000;
if(isNaN(process.argv[2])) { process.argv[2] = defaultPort; }
var port = process.argv[2] || defaultPort;

// Start the Server
server.listen(process.env.PORT || port, process.env.IP || '0.0.0.0', function() {
  var address = server.address();
  console.log('Proxy server is running on ', address.address + ':' + address.port);
});
<commit_msg>Add 404 status message if url mapping not found<commit_after>// Require the http module and the proxy module
var http      = require('http'),
    httpProxy = require('http-proxy'),
    url       = require('url');
    routes    = require('./config/routes');

console.log(routes);
// Create the proxy
var proxy = httpProxy.createProxyServer({});

// Setup the proxy server and determine routing
var server = http.createServer(function(req, res) {
  var rqstUrl = req.headers.host;
  console.log(rqstUrl);
  if(routes[rqstUrl]) {
    target_address = routes.ipaddress + routes[rqstUrl].target;
    proxy.web(req, res, { target: target_address });
  }
  else {
    res.statusCode = 404;
    res.statusMessage = '404: Not found';
    res.end();
  }
});

// Determine the port number
var defaultPort = 3000;
if(isNaN(process.argv[2])) { process.argv[2] = defaultPort; }
var port = process.argv[2] || defaultPort;

// Start the Server
server.listen(process.env.PORT || port, process.env.IP || '0.0.0.0', function() {
  var address = server.address();
  console.log('Proxy server is running on ', address.address + ':' + address.port);
});
<|endoftext|>


<commit_before>/*global require, console, process */
(function () {

    'use strict';

    /**
     * Define empty 'lm' object.
     */
    var lm = {};

    /**
     * Load necessary npm modules.
     * @type {{cylon: Object, fs: Object, util: Object, serialport: Object}}
     */
    lm.modules = {
        cylon: require('cylon'),
        fs: require('fs'),
        util: require('util'),
        serialport: require('serialport')
    };

    lm.config = {
        serial: {
            baudrate: 115200
        }
    };

    lm.app = {

        /**
         * Various app states.
         */
        states: {
            isPalmOpen: true
        },

        /**
         * Init Cylon.js module
         * and define the all needed
         * devices and connections.
         */
        cylon: lm.modules.cylon.robot({
            connections: {
                leapmotion: {
                    adaptor: 'leapmotion'
                }
            },
            devices: {
                leapmotion: {
                    driver: 'leapmotion'
                }
            },
            work: function (my) {
                /**
                 * Handling 'hand' event
                 * from Leap Motion controller.
                 */
                my.leapmotion.on('hand', function (payload) {

                    var straightFingers = 0,
                        isPalmOpen;

                    /**
                     * Iterate the all fingers.
                     */
                    payload.fingers.forEach(function (finger) {
                        /**
                         * If finger is straight,
                         * we should increase the value
                         * of 'straightFinters' with 1.
                         */
                        if (finger.extended) {
                            /**
                             * Calculate straight fingers.
                             * @type {number}
                             */
                            straightFingers = straightFingers + 1;
                        }
                    });

                    /**
                     * Where the 'straightFingers' number
                     * is equal to or greater than 4,
                     * we should presume that the palm is open.
                     * @type {boolean}
                     */
                    isPalmOpen = straightFingers >= 4;

                    /**
                     * If the current state is different
                     * than previous one, update it
                     * and send the necessary data using serial port.
                     */
                    if (lm.app.states.isPalmOpen !== isPalmOpen) {
                        lm.app.states.isPalmOpen = isPalmOpen;
                        lm.app.serial.router.write(isPalmOpen.toString());
                        console.log('Palm is %s', isPalmOpen ? 'open' : 'closed');
                    }
                });
            }
        }),
        serial: {
            router: null,
            start: function (port) {
                /**
                 * Init the serial communication
                 * on port described with 'port' attribute.
                 * @type {*|SerialPort}
                 */
                lm.app.serial.router = new lm.modules.serialport.SerialPort(port, {
                    baudrate: lm.config.serial.baudrate
                }, true);

                /**
                 * Monitor serial port states.
                 */
                lm.app.serial.router.on('open', function () {
                    console.log('SerialPort opened on %s', port);

                    /**
                     * Start Cylon library
                     * if the serial communication is established.
                     */
                    lm.app.cylon.start();
                });

                lm.app.serial.router.on('close', function () {
                    console.log('SerialPort closed.');
                });
            }
        },
        start: function () {

            /**
             * List the all available USB devices
             * and find the Arduino compatible board.
             */
            lm.modules.serialport.list(function (err, ports) {

                if (err) {
                    throw new Error(err.message);
                }

                /**
                 * Filter Arduino compatible devices.
                 */
                var arduino = ports.filter(function (port) {
                    return [/^arduino/i].test(port.manufacturer);
                });

                /**
                 * Behavior depends on the number of compatible devices.
                 */
                switch (arduino.length) {

                    // No Arduino compatible device...
                    case 0:
                        console.error('Plug in your Arduino board first!');
                        process.exit();
                        break;

                    // We found the one and only Arduino device...
                    case 1:
                        var board = arduino.pop();
                        console.log('Connecting to Arduino board %s on port %s', board.manufacturer, board.comName);
                        lm.app.serial.start(board.comName);
                        break;

                    // Otherwise...
                    default:
                        console.error('There is more than one Arduino board plugged into your computer. Please reduce it to ONE!');
                        process.exit();
                }

            });

        }
    };

    lm.app.start();

    /**
     * Kill app on CTRL+C
     */
    process.on('SIGINT', function () {
        console.info('Bye!');
        lm.app.serial.router.close();
        process.exit();
    });
}());<commit_msg>Bugfix for RegExp pattern.<commit_after>/*global require, console, process */
(function () {

    'use strict';

    /**
     * Define empty 'lm' object.
     */
    var lm = {};

    /**
     * Load necessary npm modules.
     * @type {{cylon: Object, fs: Object, util: Object, serialport: Object}}
     */
    lm.modules = {
        cylon: require('cylon'),
        fs: require('fs'),
        util: require('util'),
        serialport: require('serialport')
    };

    lm.config = {
        serial: {
            baudrate: 115200
        }
    };

    lm.app = {

        /**
         * Various app states.
         */
        states: {
            isPalmOpen: true
        },

        /**
         * Init Cylon.js module
         * and define the all needed
         * devices and connections.
         */
        cylon: lm.modules.cylon.robot({
            connections: {
                leapmotion: {
                    adaptor: 'leapmotion'
                }
            },
            devices: {
                leapmotion: {
                    driver: 'leapmotion'
                }
            },
            work: function (my) {
                /**
                 * Handling 'hand' event
                 * from Leap Motion controller.
                 */
                my.leapmotion.on('hand', function (payload) {

                    var straightFingers = 0,
                        isPalmOpen;

                    /**
                     * Iterate the all fingers.
                     */
                    payload.fingers.forEach(function (finger) {
                        /**
                         * If finger is straight,
                         * we should increase the value
                         * of 'straightFinters' with 1.
                         */
                        if (finger.extended) {
                            /**
                             * Calculate straight fingers.
                             * @type {number}
                             */
                            straightFingers = straightFingers + 1;
                        }
                    });

                    /**
                     * Where the 'straightFingers' number
                     * is equal to or greater than 4,
                     * we should presume that the palm is open.
                     * @type {boolean}
                     */
                    isPalmOpen = straightFingers >= 4;

                    /**
                     * If the current state is different
                     * than previous one, update it
                     * and send the necessary data using serial port.
                     */
                    if (lm.app.states.isPalmOpen !== isPalmOpen) {
                        lm.app.states.isPalmOpen = isPalmOpen;
                        lm.app.serial.router.write(isPalmOpen.toString());
                        console.log('Palm is %s', isPalmOpen ? 'open' : 'closed');
                    }
                });
            }
        }),
        serial: {
            router: null,
            start: function (port) {
                /**
                 * Init the serial communication
                 * on port described with 'port' attribute.
                 * @type {*|SerialPort}
                 */
                lm.app.serial.router = new lm.modules.serialport.SerialPort(port, {
                    baudrate: lm.config.serial.baudrate
                }, true);

                /**
                 * Monitor serial port states.
                 */
                lm.app.serial.router.on('open', function () {
                    console.log('SerialPort opened on %s', port);

                    /**
                     * Start Cylon library
                     * if the serial communication is established.
                     */
                    lm.app.cylon.start();
                });

                lm.app.serial.router.on('close', function () {
                    console.log('SerialPort closed.');
                });
            }
        },
        start: function () {

            /**
             * List the all available USB devices
             * and find the Arduino compatible board.
             */
            lm.modules.serialport.list(function (err, ports) {

                if (err) {
                    throw new Error(err.message);
                }

                /**
                 * Filter Arduino compatible devices.
                 */
                var arduino = ports.filter(function (port) {
                    return (/^arduino/i).test(port.manufacturer);
                });

                /**
                 * Behavior depends on the number of compatible devices.
                 */
                switch (arduino.length) {

                    // No Arduino compatible device...
                    case 0:
                        console.error('Plug in your Arduino board first!');
                        process.exit();
                        break;

                    // We found the one and only Arduino device...
                    case 1:
                        var board = arduino.pop();
                        console.log('Connecting to Arduino board %s on port %s', board.manufacturer, board.comName);
                        lm.app.serial.start(board.comName);
                        break;

                    // Otherwise...
                    default:
                        console.error('There is more than one Arduino board plugged into your computer. Please reduce it to ONE!');
                        process.exit();
                }

            });

        }
    };

    lm.app.start();

    /**
     * Kill app on CTRL+C
     */
    process.on('SIGINT', function () {
        console.info('Bye!');
        lm.app.serial.router.close();
        process.exit();
    });
}());<|endoftext|>


<commit_before>/** Main application file
 * Kicks off the whole show
 */

var   express = require('express')
    , fs = require('fs')
    , auth = require('./lib/authorization')
    , utils = require('./lib/utils')
    , app = express()
    , port = (typeof process !== "undefined" && process !== null ? (_ref2 = process.env) !== null ? _ref2.PORT : undefined : undefined) || 80
    , sio = require('socket.io')
    , io
    , mongoose = require('mongoose')
    , mixpanel = new require('mixpanel').init(process.env.COURSESHARK_MIXPANEL_ACCESS_TOKEN)

console.log("\n\nStarting in mode:", app.settings.env);

app.config = process.env;
app.mixpanel = mixpanel;
app.mixpanel.set_config({ test: (process.env.COURSESHARK_MIXPANEL_TEST||'').match(/true/i)
                        , debug: (process.env.COURSESHARK_MIXPANEL_DEBUG||'').match(/true/i)});

// Socket.io
httpForSocket = require('http').createServer(app)
app.io = io = sio.listen(httpForSocket);
app.io.enable('browser client minification');  // send minified client
app.io.enable('browser client etag');          // apply etag caching logic based on version number
app.io.enable('browser client gzip');          // gzip the file
app.io.set('log level', 1);                    // reduce logging
app.io.set('transports',['websocket']);        // enable all transports (optional if you want flashsocket)
// Setup RedisStore for shared sockets
if (process.env.COURSESHARK_REDIS_URI){
  var info = require('url').parse(process.env.COURSESHARK_REDIS_URI)
    , RedisStore = require('socket.io/lib/stores/redis')
    , redis  = require('socket.io/node_modules/redis')
    , pub    = redis.createClient(info.port, info.hostname)
    , sub    = redis.createClient(info.port, info.hostname)
    , client = redis.createClient(info.port, info.hostname)
  console.log("Using Redis for socket.io store");
  app.io.set('store', new RedisStore({
    redisPub : pub
  , redisSub : sub
  , redisClient : client
  }));
}

mongoose.connection.on('open', function(){
  console.log('Database Connected');
  Schema = mongoose.Schema;
  ObjectId = mongoose.Types.ObjectId;
  // Bootsrap models
  model_loc = __dirname + '/models';
  model_files = fs.readdirSync(model_loc);
  model_files.forEach( function (file) {
    require(model_loc + '/' + file).boot(app);
  })
  require('./lib/social-track').boot(app);
  // Configuration
  require('./lib/flipflop').boot(app, mongoose, function(){
    // Configuration
    require('./lib/settings').boot(app, mongoose);
    //Error Handler
    require('./lib/error-handler').boot(app);
    // make a global helper
    requireLogin = auth.requireLogin;
    requireAdmin = auth.requireAdmin;
    requireSchool = utils.requireSchool;
    wantSchool = utils.wantSchool;
    // Bootstrap controllers
    controller_loc = __dirname + '/controllers';
    controller_files = fs.readdirSync(controller_loc);
    controller_files.forEach( function (file) {
      require(controller_loc + '/' + file)(app);
    })
    // Build
    require('./build').build(app);
    // Start the app by listening on <port>
    app.listen(port);
    console.log('CourseShark started on port ' + port);
  });
})

// Connect to the Database
mongoose.connect(process.env.COURSESHARK_MONGODB_URI);
<commit_msg>Fixed binding issued with socket.io<commit_after>/** Main application file
 * Kicks off the whole show
 */

var   express = require('express')
    , fs = require('fs')
    , auth = require('./lib/authorization')
    , utils = require('./lib/utils')
    , app = express()
    , port = process.env.PORT || 8080
    , sio = require('socket.io')
    , io
    , mongoose = require('mongoose')
    , mixpanel = new require('mixpanel').init(process.env.COURSESHARK_MIXPANEL_ACCESS_TOKEN)

console.log("\n\nStarting in mode:", app.settings.env);

app.config = process.env;
app.mixpanel = mixpanel;
app.mixpanel.set_config({ test: (process.env.COURSESHARK_MIXPANEL_TEST||'').match(/true/i)
                        , debug: (process.env.COURSESHARK_MIXPANEL_DEBUG||'').match(/true/i)});

mongoose.connection.on('open', function(){
  console.log('Database Connected');
  Schema = mongoose.Schema;
  ObjectId = mongoose.Types.ObjectId;
  // Bootsrap models
  model_loc = __dirname + '/models';
  model_files = fs.readdirSync(model_loc);
  model_files.forEach( function (file) {
    require(model_loc + '/' + file).boot(app);
  })
  require('./lib/social-track').boot(app);
  // Configuration
  require('./lib/flipflop').boot(app, mongoose, function(){

    // Configuration
    require('./lib/settings').boot(app, mongoose);

    //Error Handler
    require('./lib/error-handler').boot(app);

    // make a global helper
    requireLogin = auth.requireLogin;
    requireAdmin = auth.requireAdmin;
    requireSchool = utils.requireSchool;
    wantSchool = utils.wantSchool;

    // Start the app by listening on <port>
    var server = app.listen(port);
    // Socket.io
    app.io = io = sio.listen(server);
    app.io.enable('browser client minification');  // send minified client
    app.io.enable('browser client etag');          // apply etag caching logic based on version number
    app.io.enable('browser client gzip');          // gzip the file
    app.io.set('log level', 1);                    // reduce logging
    app.io.set('transports',['websocket']);        // enable all transports (optional if you want flashsocket)
    // Setup RedisStore for shared sockets
    if (process.env.COURSESHARK_REDIS_URI){
      var info = require('url').parse(process.env.COURSESHARK_REDIS_URI)
        , RedisStore = require('socket.io/lib/stores/redis')
        , redis  = require('socket.io/node_modules/redis')
        , pub    = redis.createClient(info.port, info.hostname)
        , sub    = redis.createClient(info.port, info.hostname)
        , client = redis.createClient(info.port, info.hostname)
      console.log("Using Redis for socket.io store");
      app.io.set('store', new RedisStore({
        redisPub : pub
      , redisSub : sub
      , redisClient : client
      }));
    }

    // Bootstrap controllers
    controller_loc = __dirname + '/controllers';
    controller_files = fs.readdirSync(controller_loc);
    controller_files.forEach( function (file) {
      require(controller_loc + '/' + file)(app);
    })

    // Build
    require('./build').build(app);

    console.log('CourseShark started on port ' + port);
  });
})

// Connect to the Database
mongoose.connect(process.env.COURSESHARK_MONGODB_URI);
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
<commit_msg>updates<commit_after>/**
 *Blobber Server
 *Written by Sandeep Vattapparambil
 *sandeepv68@gmail.com
 */
/*Express Module Import*/
var express = require('express');
/*Path Module for file I/O*/
var path = require('path');
/*Favicon Module*/
var favicon = require('serve-favicon');
/*Morgan Logger Module*/
var logger = require('morgan');
/*Cookie-Parser Module*/
var cookieParser = require('cookie-parser');
/*URL Parameter parsing Module*/
var bodyParser = require('body-parser');

/*index routes*/
var index = require('./routes/index');
/*user routes*/
var users = require('./routes/users');

/*Instantiate Express Module*/
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
//EJS view engine is used
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
<|endoftext|>


<commit_before>var config = require('./config.js');
var ip = config.ip;
var port = config.port;
var express = require('express');
var app = express();
var server = app.listen(port);
var ejs = require('ejs');
var bbcode = require('bbcode');
var io = require('socket.io').listen(server);
io.set('log level', 1);
var sys = require('sys')
var exec = require('child_process').exec;

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));

process.on('SIGINT', function() {
  console.log( "\nShutting down from manual SIGINT (Ctrl-C), NOW." );
  io.sockets.emit('annouce', {message : 'SHUTTING DOWN, NOW!'});
  process.exit();
});

process.once('SIGUSR2', function () {
  gracefulShutdown(function () {
    process.kill(process.pid, 'SIGUSR2');
  });
});

function gracefulShutdown(kill){
  console.log( "\nShutting down from nodemon SUGUSR2 (RESTART) in 10 seconds..." );
  io.sockets.emit('annouce', {message : 'RESTARTING IN 10 SECONDS!'});
  setTimeout(function(){kill()}, 10000);
}

app.post('/gitpull', function(req, res) {
  //GitHub push hook
  res.end();
  function puts(error, stdout, stderr) {sys.puts(stdout)}
  exec("git reset --hard HEAD", puts);
  exec("git pull", puts);
});

app.get('*', function(req, res) {
  res.render('index.ejs', {
   ip: ip
 });
});

var users = [];

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
 io.sockets.emit('annouce', {message : '' + chunk.toUpperCase() + ''});
});

io.sockets.on('connection', function (socket) {
  function broadcast(data) {
    io.sockets.emit('annouce', {message : data});
  }

  function parseServerCommand(data) {
    var res = data.message.trim().split(" ");

    if(res[0].toLowerCase() == "/nick"){
      updateName(res.slice(1,res.length).join(' '));
      return;
    }

    if(res[0].toLowerCase() == "/pm"){
      if(res.length >= 3){
        if(res[1] == 'SERVER'){
          var help = "You cannot PM the server.";
          socket.emit('annouce', {message : help});
          return;
        }
        if(findUser(res[1])){
          pm(res[1], res.slice(2, res.length).join(' '));
          return;
        } else if (findUser(res.slice(1 ,3).join(' '))){
          pm(res.slice(1 ,3).join(' '), res.slice(3, res.length).join(' '));
          return;
        } else {
          var help = "User not found for command '" + res.join(' ') + "'";
          socket.emit('annouce', {message : help});
        }
      } else {
          var help = "You must add a PM message.";
          socket.emit('annouce', {message : help});
      }
    }

    if(res[0].toLowerCase() == "/disconnect"){
      socket.disconnect();
    }

    if(res[0].toLowerCase() == "/help"){
      sendHelp();
      return;
    }

    unrecognized(res[0]);
    sendHelp();
  }

  var entityMap = {
    "&": "&",
    "<": "<",
    ">": ">",
    '"': '"',
    "'": ''',
    "/": '/'
  };

  function escapeHtml(string) {
    return String(string).replace(/[&<>"'\/]/g, function (s) {
      return entityMap[s];
    });
  }

  function removeItem(arr, item) {
    for(var i = arr.length; i--;) {
      if(arr[i][0].toString() === item[0].toString()) {
        arr.splice(i, 1);
      }
    }
  }

  function findUser(user) {
    for(var i = users.length; i--;) {
      if(users[i][0] == user) {
        return true;
      }
    }
    return false;
  }

  function findSocket(user) {
    for(var i = users.length; i--;) {
      if(users[i][0] == user) {
        return users[i][1];
      }
    }
    return 0;
  }

  function pm(dest, data){
    if(dest == name){
      var help = "You cannot PM yourself.";
      socket.emit('annouce', {message : help});
      return;
    }
    data = '<to ' + dest + '> ' + data + '</span';
    io.sockets.socket(findSocket(dest)).emit('broadcast', {client : name, message : data});
    socket.emit('broadcast', {client : name, message : data});
  }

  function updateName(data){
    if(findUser(data)){
      socket.emit('annouce', {message : "The nick '" + data + "' is taken!"});
      return;
    }
    if(data.toLowerCase() == "admin" || data.toLowerCase() == "server"){
      socket.emit('annouce', {message : "That nick is reserved!"});
      return;
    }
    oldName = name;
    name = data;
    removeItem(users, [oldName, socket.id]);
    users.push([name, socket.id, true]);
    io.sockets.emit('users', users);
    socket.emit('name', {name : name});
    broadcast('' + oldName + ' has changed name to ' + data + '.');
  }

  function disconnect(data){
    socket.disconnect();
  }

  function unrecognized(data){
    var help = "Unknown command '" + data + "'.";
    socket.emit('annouce', {message : help});
  }

  function sendHelp(){
    var help = "HardOrange IRC Help - Commands:
/nick nick
/pm nick message
/clear
/disconnect
/help";
    socket.emit('annouce', {message : help});
  }

  function multiArrayIndex(arr, item){
    for(var i = 0; i < arr.length; i++) {
      if(arr[i].toString() == item.toString()) {
          return i;
       }
     }
  }

  //Set name and notify clients
  sendHelp();
  var name = 'Guest' + Math.floor(100 + Math.random() * 900);
  broadcast('' + name + ' has entered chat.');
  users.push([name, socket.id, true]);
  io.sockets.emit('users', users);
  socket.emit('name', {name : name});

  //Begin Handlers
  socket.on('broadcast', function (data) {
    if(data.message[0] == "/") {
      parseServerCommand(data);
    } else {
      bbcode.parse(escapeHtml(data.message), function(content){
        io.sockets.emit('broadcast', {client : name, message : content});
      });
    }
  });

  socket.on('status', function (data) {
    var index = multiArrayIndex(users, [name, socket.id, !data.status]);
    users[index][2] = data.status;
    io.sockets.emit('users', users);
  });

  socket.on('disconnect', function (data) {
    removeItem(users, [name, socket.id]);
    io.sockets.emit('users', users);
    broadcast('' + name + ' has exited chat.');
  });
});
<commit_msg>Error catching for status<commit_after>var config = require('./config.js');
var ip = config.ip;
var port = config.port;
var express = require('express');
var app = express();
var server = app.listen(port);
var ejs = require('ejs');
var bbcode = require('bbcode');
var io = require('socket.io').listen(server);
io.set('log level', 1);
var sys = require('sys')
var exec = require('child_process').exec;

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));

process.on('SIGINT', function() {
  console.log( "\nShutting down from manual SIGINT (Ctrl-C), NOW." );
  io.sockets.emit('annouce', {message : 'SHUTTING DOWN, NOW!'});
  process.exit();
});

process.once('SIGUSR2', function () {
  gracefulShutdown(function () {
    process.kill(process.pid, 'SIGUSR2');
  });
});

function gracefulShutdown(kill){
  console.log( "\nShutting down from nodemon SUGUSR2 (RESTART) in 10 seconds..." );
  io.sockets.emit('annouce', {message : 'RESTARTING IN 10 SECONDS!'});
  setTimeout(function(){kill()}, 10000);
}

app.post('/gitpull', function(req, res) {
  //GitHub push hook
  res.end();
  function puts(error, stdout, stderr) {sys.puts(stdout)}
  exec("git reset --hard HEAD", puts);
  exec("git pull", puts);
});

app.get('*', function(req, res) {
  res.render('index.ejs', {
   ip: ip
 });
});

var users = [];

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
 io.sockets.emit('annouce', {message : '' + chunk.toUpperCase() + ''});
});

io.sockets.on('connection', function (socket) {
  function broadcast(data) {
    io.sockets.emit('annouce', {message : data});
  }

  function parseServerCommand(data) {
    var res = data.message.trim().split(" ");

    if(res[0].toLowerCase() == "/nick"){
      updateName(res.slice(1,res.length).join(' '));
      return;
    }

    if(res[0].toLowerCase() == "/pm"){
      if(res.length >= 3){
        if(res[1] == 'SERVER'){
          var help = "You cannot PM the server.";
          socket.emit('annouce', {message : help});
          return;
        }
        if(findUser(res[1])){
          pm(res[1], res.slice(2, res.length).join(' '));
          return;
        } else if (findUser(res.slice(1 ,3).join(' '))){
          pm(res.slice(1 ,3).join(' '), res.slice(3, res.length).join(' '));
          return;
        } else {
          var help = "User not found for command '" + res.join(' ') + "'";
          socket.emit('annouce', {message : help});
        }
      } else {
          var help = "You must add a PM message.";
          socket.emit('annouce', {message : help});
      }
    }

    if(res[0].toLowerCase() == "/disconnect"){
      socket.disconnect();
    }

    if(res[0].toLowerCase() == "/help"){
      sendHelp();
      return;
    }

    unrecognized(res[0]);
    sendHelp();
  }

  var entityMap = {
    "&": "&",
    "<": "<",
    ">": ">",
    '"': '"',
    "'": ''',
    "/": '/'
  };

  function escapeHtml(string) {
    return String(string).replace(/[&<>"'\/]/g, function (s) {
      return entityMap[s];
    });
  }

  function removeItem(arr, item) {
    for(var i = arr.length; i--;) {
      if(arr[i][0].toString() === item[0].toString()) {
        arr.splice(i, 1);
      }
    }
  }

  function findUser(user) {
    for(var i = users.length; i--;) {
      if(users[i][0] == user) {
        return true;
      }
    }
    return false;
  }

  function findSocket(user) {
    for(var i = users.length; i--;) {
      if(users[i][0] == user) {
        return users[i][1];
      }
    }
    return 0;
  }

  function pm(dest, data){
    if(dest == name){
      var help = "You cannot PM yourself.";
      socket.emit('annouce', {message : help});
      return;
    }
    data = '<to ' + dest + '> ' + data + '</span';
    io.sockets.socket(findSocket(dest)).emit('broadcast', {client : name, message : data});
    socket.emit('broadcast', {client : name, message : data});
  }

  function updateName(data){
    if(findUser(data)){
      socket.emit('annouce', {message : "The nick '" + data + "' is taken!"});
      return;
    }
    if(data.toLowerCase() == "admin" || data.toLowerCase() == "server"){
      socket.emit('annouce', {message : "That nick is reserved!"});
      return;
    }
    oldName = name;
    name = data;
    removeItem(users, [oldName, socket.id]);
    users.push([name, socket.id, true]);
    io.sockets.emit('users', users);
    socket.emit('name', {name : name});
    broadcast('' + oldName + ' has changed name to ' + data + '.');
  }

  function disconnect(data){
    socket.disconnect();
  }

  function unrecognized(data){
    var help = "Unknown command '" + data + "'.";
    socket.emit('annouce', {message : help});
  }

  function sendHelp(){
    var help = "HardOrange IRC Help - Commands:
/nick nick
/pm nick message
/clear
/disconnect
/help";
    socket.emit('annouce', {message : help});
  }

  function multiArrayIndex(arr, item){
    for(var i = 0; i < arr.length; i++) {
      if(arr[i].toString() == item.toString()) {
          return i;
       }
     }
  }

  //Set name and notify clients
  sendHelp();
  var name = 'Guest' + Math.floor(100 + Math.random() * 900);
  broadcast('' + name + ' has entered chat.');
  users.push([name, socket.id, true]);
  io.sockets.emit('users', users);
  socket.emit('name', {name : name});

  //Begin Handlers
  socket.on('broadcast', function (data) {
    if(data.message[0] == "/") {
      parseServerCommand(data);
    } else {
      bbcode.parse(escapeHtml(data.message), function(content){
        io.sockets.emit('broadcast', {client : name, message : content});
      });
    }
  });

  socket.on('status', function (data) {
    var index = multiArrayIndex(users, [name, socket.id, !data.status]);
    if(index === undefined){console.log('missing user');console.log(data);return;}
    users[index][2] = data.status;
    io.sockets.emit('users', users);
  });

  socket.on('disconnect', function (data) {
    removeItem(users, [name, socket.id]);
    io.sockets.emit('users', users);
    broadcast('' + name + ' has exited chat.');
  });
});
<|endoftext|>


<commit_before>#!/bin/env node

/* Add modules */
var express = require('express'),
	app = express(),
	fs = require('fs'),
	http = require('http'),
	jade = require('jade'),
	routes = require('./routes'),
	passport = require('passport'),
	user = require('./routes/user'),
	flash = require('connect-flash'),
	email = require("./config/email"),
	db = require("./config/database"),
	config = require("./config/config"),
	auth = require("./config/authentication"),
	MongoStore = require('connect-mongo')(express),
	expressValidator = require('express-validator');

var SessionStore = new MongoStore({ url: config.database_url });
/* Set app properties */
app.set('view engine', 'jade');
app.use(express.static(__dirname + "/public"));
app.use(express.json());
app.use(express.urlencoded());
app.use(expressValidator());
app.use(express.logger('dev'));
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
	secret: "super-secret-u-will-never-guess",
	store: SessionStore
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);

// development only
if ('development' == app.get('env')) {
	app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
}

app.get("/login", auth.checkLogin, user.login);
app.all("/register", auth.checkLogin, user.register);
app.get("/register/:id", auth.checkLogin, user.verify);
app.all("/forgot", auth.checkLogin, user.forgotPassword);
app.get("/study", routes.study);
app.get("/coding", routes.coding);
app.get("/sumorobot", routes.sumorobot);

app.post("/login", passport.authenticate("local", { successRedirect: "/profile", failureRedirect: "/login", failureFlash: true }));

app.get(config.google.auth, passport.authenticate("google", { scope: config.google.gdata_scopes }));
app.get(config.google.callback, passport.authenticate("google", { successRedirect: "/profile", failureRedirect: "/login", failureFlash: true }));

app.get(config.twitter.auth, passport.authenticate("twitter"));
app.get(config.twitter.callback, passport.authenticate("twitter", { successRedirect: "/profile", failureRedirect: "/login", failureFlash: true }));

/* Facebook Oauth2 bug appends #_=_ to the callback URL */
app.get(config.facebook.auth, passport.authenticate("facebook", { scope: ['email'] }));
app.get(config.facebook.callback, passport.authenticate("facebook", { successRedirect: "/profile", failureRedirect: "/login", failureFlash: true }));

app.get(config.linkedin.auth, passport.authenticate("linkedin", { scope: ['r_basicprofile', 'r_emailaddress'] }));
app.get(config.linkedin.callback, passport.authenticate("linkedin", { successRedirect: "/profile", failureRedirect: "/login", failureFlash: true }));

app.get(config.github.auth, passport.authenticate("github"));
app.get(config.github.callback, passport.authenticate("github", { successRedirect: "/profile", failureRedirect: "/login", failureFlash: true }));

app.get("/logout", user.logout);

/* Homepage */
app.get("/", auth.ensureAuthenticated, routes.index);

/* Profile page */
app.get("/profile", auth.ensureAuthenticated, user.profile);
app.post("/profile/update", auth.ensureAuthenticated, user.profileUpdate);
app.post("/profile/password", auth.ensureAuthenticated, user.passwordUpdate);
app.get("/profile/mugshot/:provider", auth.ensureAuthenticated, user.mugshotUpdate);
app.get("/profile/remove/:name", auth.ensureAuthenticated, user.providerRemove);

/* Delete all the users and providers */
if (false) {
	db.User.remove(function (err, removed) {
		if (err) console.log("ERROR", "deleting all users:", err);
		else console.log("INFO", "successfully removed all users");
	});
	db.Provider.remove(function (err, removed) {
		if (err) console.log("ERROR", "deleting all providers:", err);
		else console.log("INFO", "successfully removed all providers");
	});
}

/* Show all the users and providers */
db.User.find(function (err, users) {
	if (err) console.log("ERROR", "fetching all users:", err);
	else users.forEach(function(user) {
		console.log("INFO", "user name:", user.name);
	});
});
db.Provider.find(function (err, providers) {
	if (err) console.log("ERROR", "fetching all providers:", err);
	else providers.forEach(function(provider) {
		console.log("INFO", "provider url:", provider.url);
	});
});

/* Start the app */
var server = http.createServer(app).listen(config.port);
console.log("INFO", "express server listening on port:", config.port);

/* Setup socket sessionstore */
var io = require('socket.io').listen(server);
var ss = require('socket.io-stream');

var passportSocketIo = require('passport.socketio');
io.set('authorization', passportSocketIo.authorize({
	cookieParser: express.cookieParser,
	key: 'connect.sid',
	secret: 'super-secret-u-will-never-guess',
	store: SessionStore,
	fail: function(data, accept) {
		console.log("ERROR", "scoket data:", data);
		accept(null, false);
	},
	success: function(data, accept) {
		//console.log("INFO", "scoket:", data);
		accept(null, true);
	}
}));

/* Online users */
var onlineUsers = {};
var currentTask = 0;
var task = [
	"Task 1: Create a basic html structure with head and body",
	"Task 2: Add a header 1 with text 'Awesome' inside the body",
	"Task 3: Add two paragraph under the header 1, the first with text 'Cool' and second with text 'Interesting'",
	"Task 4: Add a link with text 'My Website' and link 'http://www.mywebsite.com', after the paragraphs"];
var taskVerify = [
	'(.*)',
	'(.*)
Awesome
',
	'(.*)
Awesome

Cool

Interesting
',
	'(.*)
Awesome

Cool

Interesting
<ahref="http://www.mywebsite.com">MyWebsite'];
/* User initiated socket connection */
io.sockets.on('connection', function (socket) {
	/* Add user to online users */
	console.log("INFO", "socket connection established");
	console.log("INFO", "socket user:", socket.handshake.user.email);
	onlineUsers[socket.handshake.user.email] = {
		name: socket.handshake.user.name,
		email: socket.handshake.user.email,
		profile: {
			mugshot: socket.handshake.user.profile.mugshot,
			website: socket.handshake.user.profile.website,
			description: socket.handshake.user.profile.description
		}
	};
	/* Update the online users for all users */
	io.sockets.emit("users", onlineUsers);

	/* User asks for someones code */
	socket.on('ping', function() {
		console.log("INFO", "ping received from user:", socket.handshake.user.email);
	});

	/* User asks for someones code */
	socket.on('get-code', function(userEmail) {
		console.log("INFO", "get user code:", userEmail);
		socket.emit("receive-code", onlineUsers[userEmail].code);
	});

	/* User asks for a task */
	socket.on('get-task', function() {
		console.log("INFO", "get task:", socket.handshake.user.email);
		socket.emit("receive-task", task[currentTask]);
	});

	/* User verifies a task */
	socket.on('verify-task', function(code) {
		console.log("INFO", "verifiying task:", code.replace(/\s+/g, ''));
		/* Save the users code */
		onlineUsers[socket.handshake.user.email].code = code;
		if (code.replace(/\s+/g, '').match(taskVerify[currentTask])) {
			io.sockets.emit("receive-task-verification", socket.handshake.user.name);
			/* Update the current task */
			currentTask = (currentTask + 1) % task.length;
			io.sockets.emit("receive-task", task[currentTask]);
		}
		else
			io.sockets.emit("receive-task-verification", "");
	});

	/* To stream mugshot to the server */
	ss(socket).on('mugshot', function(stream, meta) {
		console.log("INFO", "incoming stream size:", meta.size, meta.name)
		/* Drop the stream if the file is too large max 100KB allowed */
		if (meta.size > 100000) return;
		stream.pipe(fs.createWriteStream(__dirname + '/public/images/' + meta.name));
		// Send progress back
		ss(socket).emit('data', "Mugshot uploaded, click save to update");
	});

	/* User disconnected from socket */
	socket.on('disconnect', function() {
		console.log("INFO", "socket user disconnected:", socket.handshake.user.email);
		/* Delete user from online users */
		delete onlineUsers[socket.handshake.user.email];
		/* Update the online users for all users */
		io.sockets.emit("users", onlineUsers);
		/* TODO: Try to reconnect */
	});
});<commit_msg>socket fix<commit_after>#!/bin/env node

/* Add modules */
var express = require('express'),
	app = express(),
	fs = require('fs'),
	http = require('http'),
	jade = require('jade'),
	routes = require('./routes'),
	passport = require('passport'),
	user = require('./routes/user'),
	flash = require('connect-flash'),
	email = require("./config/email"),
	db = require("./config/database"),
	config = require("./config/config"),
	auth = require("./config/authentication"),
	MongoStore = require('connect-mongo')(express),
	expressValidator = require('express-validator');

var SessionStore = new MongoStore({ url: config.database_url });
/* Set app properties */
app.set('view engine', 'jade');
app.use(express.static(__dirname + "/public"));
app.use(express.json());
app.use(express.urlencoded());
app.use(expressValidator());
app.use(express.logger('dev'));
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
	secret: "super-secret-u-will-never-guess",
	store: SessionStore
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);

// development only
if ('development' == app.get('env')) {
	app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
}

app.get("/login", auth.checkLogin, user.login);
app.all("/register", auth.checkLogin, user.register);
app.get("/register/:id", auth.checkLogin, user.verify);
app.all("/forgot", auth.checkLogin, user.forgotPassword);
app.get("/study", routes.study);
app.get("/coding", routes.coding);
app.get("/sumorobot", routes.sumorobot);

app.post("/login", passport.authenticate("local", { successRedirect: "/profile", failureRedirect: "/login", failureFlash: true }));

app.get(config.google.auth, passport.authenticate("google", { scope: config.google.gdata_scopes }));
app.get(config.google.callback, passport.authenticate("google", { successRedirect: "/profile", failureRedirect: "/login", failureFlash: true }));

app.get(config.twitter.auth, passport.authenticate("twitter"));
app.get(config.twitter.callback, passport.authenticate("twitter", { successRedirect: "/profile", failureRedirect: "/login", failureFlash: true }));

/* Facebook Oauth2 bug appends #_=_ to the callback URL */
app.get(config.facebook.auth, passport.authenticate("facebook", { scope: ['email'] }));
app.get(config.facebook.callback, passport.authenticate("facebook", { successRedirect: "/profile", failureRedirect: "/login", failureFlash: true }));

app.get(config.linkedin.auth, passport.authenticate("linkedin", { scope: ['r_basicprofile', 'r_emailaddress'] }));
app.get(config.linkedin.callback, passport.authenticate("linkedin", { successRedirect: "/profile", failureRedirect: "/login", failureFlash: true }));

app.get(config.github.auth, passport.authenticate("github"));
app.get(config.github.callback, passport.authenticate("github", { successRedirect: "/profile", failureRedirect: "/login", failureFlash: true }));

app.get("/logout", user.logout);

/* Homepage */
app.get("/", auth.ensureAuthenticated, routes.index);

/* Profile page */
app.get("/profile", auth.ensureAuthenticated, user.profile);
app.post("/profile/update", auth.ensureAuthenticated, user.profileUpdate);
app.post("/profile/password", auth.ensureAuthenticated, user.passwordUpdate);
app.get("/profile/mugshot/:provider", auth.ensureAuthenticated, user.mugshotUpdate);
app.get("/profile/remove/:name", auth.ensureAuthenticated, user.providerRemove);

/* Delete all the users and providers */
if (false) {
	db.User.remove(function (err, removed) {
		if (err) console.log("ERROR", "deleting all users:", err);
		else console.log("INFO", "successfully removed all users");
	});
	db.Provider.remove(function (err, removed) {
		if (err) console.log("ERROR", "deleting all providers:", err);
		else console.log("INFO", "successfully removed all providers");
	});
}

/* Show all the users and providers */
db.User.find(function (err, users) {
	if (err) console.log("ERROR", "fetching all users:", err);
	else users.forEach(function(user) {
		console.log("INFO", "user name:", user.name);
	});
});
db.Provider.find(function (err, providers) {
	if (err) console.log("ERROR", "fetching all providers:", err);
	else providers.forEach(function(provider) {
		console.log("INFO", "provider url:", provider.url);
	});
});

/* Start the app */
var server = http.createServer(app).listen(config.port);
console.log("INFO", "express server listening on port:", config.port);

/* Setup socket sessionstore */
var io = require('socket.io').listen(server);
var ss = require('socket.io-stream');

// assuming io is the Socket.IO server object
io.configure(function () {
	io.set("transports", ["xhr-polling"]);
	io.set("polling duration", 10);
});

var passportSocketIo = require('passport.socketio');
io.set('authorization', passportSocketIo.authorize({
	cookieParser: express.cookieParser,
	key: 'connect.sid',
	secret: 'super-secret-u-will-never-guess',
	store: SessionStore,
	fail: function(data, accept) {
		console.log("ERROR", "scoket data:", data);
		accept(null, false);
	},
	success: function(data, accept) {
		//console.log("INFO", "scoket:", data);
		accept(null, true);
	}
}));

/* Online users */
var onlineUsers = {};
var currentTask = 0;
var task = [
	"Task 1: Create a basic html structure with head and body",
	"Task 2: Add a header 1 with text 'Awesome' inside the body",
	"Task 3: Add two paragraph under the header 1, the first with text 'Cool' and second with text 'Interesting'",
	"Task 4: Add a link with text 'My Website' and link 'http://www.mywebsite.com', after the paragraphs"];
var taskVerify = [
	'(.*)',
	'(.*)
Awesome
',
	'(.*)
Awesome

Cool

Interesting
',
	'(.*)
Awesome

Cool

Interesting
<ahref="http://www.mywebsite.com">MyWebsite'];
/* User initiated socket connection */
io.sockets.on('connection', function (socket) {
	/* Add user to online users */
	console.log("INFO", "socket connection established");
	console.log("INFO", "socket user:", socket.handshake.user.email);
	onlineUsers[socket.handshake.user.email] = {
		name: socket.handshake.user.name,
		email: socket.handshake.user.email,
		profile: {
			mugshot: socket.handshake.user.profile.mugshot,
			website: socket.handshake.user.profile.website,
			description: socket.handshake.user.profile.description
		}
	};
	/* Update the online users for all users */
	io.sockets.emit("users", onlineUsers);

	/* User asks for someones code */
	socket.on('ping', function() {
		console.log("INFO", "ping received from user:", socket.handshake.user.email);
	});

	/* User asks for someones code */
	socket.on('get-code', function(userEmail) {
		console.log("INFO", "get user code:", userEmail);
		socket.emit("receive-code", onlineUsers[userEmail].code);
	});

	/* User asks for a task */
	socket.on('get-task', function() {
		console.log("INFO", "get task:", socket.handshake.user.email);
		socket.emit("receive-task", task[currentTask]);
	});

	/* User verifies a task */
	socket.on('verify-task', function(code) {
		console.log("INFO", "verifiying task:", code.replace(/\s+/g, ''));
		/* Save the users code */
		onlineUsers[socket.handshake.user.email].code = code;
		if (code.replace(/\s+/g, '').match(taskVerify[currentTask])) {
			io.sockets.emit("receive-task-verification", socket.handshake.user.name);
			/* Update the current task */
			currentTask = (currentTask + 1) % task.length;
			io.sockets.emit("receive-task", task[currentTask]);
		}
		else
			io.sockets.emit("receive-task-verification", "");
	});

	/* To stream mugshot to the server */
	ss(socket).on('mugshot', function(stream, meta) {
		console.log("INFO", "incoming stream size:", meta.size, meta.name)
		/* Drop the stream if the file is too large max 100KB allowed */
		if (meta.size > 100000) return;
		stream.pipe(fs.createWriteStream(__dirname + '/public/images/' + meta.name));
		// Send progress back
		ss(socket).emit('data', "Mugshot uploaded, click save to update");
	});

	/* User disconnected from socket */
	socket.on('disconnect', function() {
		console.log("INFO", "socket user disconnected:", socket.handshake.user.email);
		/* Delete user from online users */
		delete onlineUsers[socket.handshake.user.email];
		/* Update the online users for all users */
		io.sockets.emit("users", onlineUsers);
		/* TODO: Try to reconnect */
	});
});<|endoftext|>