<commit_before>/**
 * Module dependencies.
 */
const express = require('express');
const compression = require('compression');
const session = require('express-session');
const bodyParser = require('body-parser');
const logger = require('morgan');
const errorHandler = require('errorhandler');
const lusca = require('lusca');
const dotenv = require('dotenv');
const MongoStore = require('connect-mongo')(session);
const flash = require('express-flash');
const path = require('path');
const mongoose = require('mongoose');
const passport = require('passport');
const expressValidator = require('express-validator');
const sass = require('node-sass-middleware');
const multer = require('multer');
const upload = multer({ dest: path.join(__dirname, 'uploads') });

/**
 * Load environment variables from .env file, where API keys and passwords are configured.
 */
dotenv.load({ path: '.env.example' });

/**
 * Controllers (route handlers).
 */
const homeController = require('./controllers/home');
const userController = require('./controllers/user');
const apiController = require('./controllers/api');
const transactionController = require('./controllers/transaction');
const contactController = require('./controllers/contact');
const messageController = require('./controllers/message');

/**
 * API keys and Passport configuration.
 */
const secrets = require('./config/secrets');
const passportConfig = require('./config/passport');
const activities = require('./config/activities');

var Message = require('./models/Message');
var Thread = require('./models/Thread');

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

var server = require('http').createServer(app);

/**
 * Connect to MongoDB.
 */
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', () => {
  console.error('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(compression());
app.use(sass({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public')
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(methodOverride());
app.use(cookieParser());
var store = new MongoStore({ url: secrets.db, autoReconnect: true });
app.use(session({
  name: 'connect.sid',
  resave: true,
  saveUninitialized: true,
  secret: secrets.sessionSecret,
  store: store
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
  if (req.path === '/api/upload') {
    next();
  } else {
    lusca.csrf()(req, res, next);
  }
});
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use((req, res, next) => {
  res.locals.user = req.user;
  next();
});
app.use((req, res, next) => {
  // After successful login, redirect back to /api, /contact or /
  if (/(api)|(contact)|(^\/$)/i.test(req.path)) {
    req.session.returnTo = req.path;
  }
  next();
});
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));

var io = require('socket.io').listen(server);
var passportSocketIo = require("passport.socketio");
var async = require('async');

function onAuthorizeSuccess(data, accept){
  console.log('successful connection to socket.io');
  accept();
}

function onAuthorizeFail(data, message, error, accept){
  console.log('failed connection to socket.io:', message);
  if(error) {
    accept(new Error(message));
  }
}

//With Socket.io >= 1.0
io.use(passportSocketIo.authorize({
  cookieParser: cookieParser,
  key:          'connect.sid',
  secret:       secrets.sessionSecret,
  store:        store,
  success:      onAuthorizeSuccess,
  fail:         onAuthorizeFail,
}));

var socket_map = {};

function saveMessage (socket, data, thread_id, callback) {
    var newMsg = new Message({
        message: data.message,
        timeSent: new Date(),
        _thread: thread_id,
        _sender: socket.request.user._id,
    });
    newMsg.save(function (err) {
        if (err) {
            throw err;
        }
        callback(null, socket, data, thread_id, newMsg)
    });
}

function sendMessage (socket, data, thread_id, newMsg, callback) {
    Thread.findOne({_id: thread_id})
    .populate('_participants')
    .exec(function (err, thread) {
        thread._participants.forEach(function (user) {
            io.to(socket_map[user._id]).emit('new message', {
                message: newMsg.message,
                timeSent: newMsg.timeSent,
                thread: thread,
                author: {
                    name: socket.request.user.profile.name,
                    pic: socket.request.user.profile.picture,
                    id: socket.request.user._id,
                    isMe: socket.request.user._id.toString() == user._id.toString(),
                },
            });
        });
        callback(null);
    });
}

function saveThread (socket, data, unused_id, callback) {
    var newThread = new Thread({
        _participants: [socket.request.user._id].concat(data.to).sort(),
        lastUpdated: new Date(),
    });

    newThread.save(function (err) {
        callback(null, socket, data, newThread._id);
    });
}

io.sockets.on('connection', function (socket) {
    socket_map[socket.request.user._id] = socket.id;
    socket.on('send message', function (data) {
        var arr = [
            saveMessage,
            sendMessage,
        ];

        if (data.isNewThread) {
            arr.unshift(saveThread);
        }

        arr.unshift(function (callback) {
            callback(null, socket, data, data.thread_id);
        })

        async.waterfall(arr, function (err, results) {
            if (err) {
                console.log("Error: " + err);
            }
        });
    });
});

/**
 * Primary app routes.
 */
app.get('/', function (req, res) {
    if (req.isAuthenticated()) {
        userController.findUsers(req, res);
    } else {
        homeController.index(req, res);
    }
});
app.get('/privacy', homeController.privacy);
app.get('/newaccount', passportConf.isAuthenticated, function (req, res) {
  res.render('account/newaccount', {
    my_skills: [],
    my_interests: [],
    activities: activities.activityMap,
  })
});
app.post('/newaccount', userController.newAccount);
app.get('/about', homeController.about);
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', passportConfig.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConfig.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConfig.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConfig.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConfig.isAuthenticated, userController.getOauthUnlink);
app.get('/messages', passportConfig.isAuthenticated, messageController.showMessages);
app.get('/_threadMessages/:id', passportConfig.isAuthenticated, messageController.getMessages);
app.get('/profile/:id', passportConfig.isAuthenticated, userController.showProfile);

app.get('/transactions', passportConf.isAuthenticated, transactionController.showTransactions);
app.post('/transactions', passportConf.isAuthenticated, transactionController.postTransaction);

app.post('/location', passportConf.isAuthenticated, userController.postLocation);

/**
 * User routes
 */
app.get('/users', passportConf.isAuthenticated, userController.findUsers);
app.get('/users/list', userController.list);

/**
 * API examples routes.
 */
app.get('/api', apiController.getApi);
app.get('/api/facebook', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getFacebook);
app.get('/api/twitter', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getTwitter);
app.post('/api/twitter', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.postTwitter);

/**
 * OAuth authentication routes. (Sign in)
 */
app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'public_profile', 'user_location', 'user_hometown'] }));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), (req, res) => {
  res.redirect(req.session.returnTo || '/account');
});
app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' }));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => {
  res.redirect(req.session.returnTo || '/account');
});
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), (req, res) => {
  res.redirect(req.session.returnTo || '/account');
});

/**
 * Error Handler.
 */
if (app.settings.env === 'production') {
  app.use(function(req, res, next){
    // the status option, or res.statusCode = 404
    // are equivalent, however with the option we
    // get the "status" local available as well
    res.status(404).render('error/404', {
      status: 404,
      url: req.url,
    });
  });
  app.use(function(err, req, res, next){
    // we may use properties of the error object
    // here and next(err) appropriately, or if
    // we possibly recovered from the error, simply next().
    res.status(500).render('error/500', {
        status: err.status || 500,
        error: err,
    });
  });
} else {
  app.use(errorHandler());
}

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

module.exports = app;
<commit_msg>Only ping socket if recipient is online<commit_after>/**
 * Module dependencies.
 */
const express = require('express');
const compression = require('compression');
const session = require('express-session');
const bodyParser = require('body-parser');
const logger = require('morgan');
const errorHandler = require('errorhandler');
const lusca = require('lusca');
const dotenv = require('dotenv');
const MongoStore = require('connect-mongo')(session);
const flash = require('express-flash');
const path = require('path');
const mongoose = require('mongoose');
const passport = require('passport');
const expressValidator = require('express-validator');
const sass = require('node-sass-middleware');
const multer = require('multer');
const upload = multer({ dest: path.join(__dirname, 'uploads') });

/**
 * Load environment variables from .env file, where API keys and passwords are configured.
 */
dotenv.load({ path: '.env.example' });

/**
 * Controllers (route handlers).
 */
const homeController = require('./controllers/home');
const userController = require('./controllers/user');
const apiController = require('./controllers/api');
const transactionController = require('./controllers/transaction');
const contactController = require('./controllers/contact');
const messageController = require('./controllers/message');

/**
 * API keys and Passport configuration.
 */
const secrets = require('./config/secrets');
const passportConfig = require('./config/passport');
const activities = require('./config/activities');

var Message = require('./models/Message');
var Thread = require('./models/Thread');

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

var server = require('http').createServer(app);

/**
 * Connect to MongoDB.
 */
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', () => {
  console.error('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(compression());
app.use(sass({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public')
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(methodOverride());
app.use(cookieParser());
var store = new MongoStore({ url: secrets.db, autoReconnect: true });
app.use(session({
  name: 'connect.sid',
  resave: true,
  saveUninitialized: true,
  secret: secrets.sessionSecret,
  store: store
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
  if (req.path === '/api/upload') {
    next();
  } else {
    lusca.csrf()(req, res, next);
  }
});
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use((req, res, next) => {
  res.locals.user = req.user;
  next();
});
app.use((req, res, next) => {
  // After successful login, redirect back to /api, /contact or /
  if (/(api)|(contact)|(^\/$)/i.test(req.path)) {
    req.session.returnTo = req.path;
  }
  next();
});
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));

var io = require('socket.io').listen(server);
var passportSocketIo = require("passport.socketio");
var async = require('async');

function onAuthorizeSuccess(data, accept){
  console.log('successful connection to socket.io');
  accept();
}

function onAuthorizeFail(data, message, error, accept){
  console.log('failed connection to socket.io:', message);
  if(error) {
    accept(new Error(message));
  }
}

//With Socket.io >= 1.0
io.use(passportSocketIo.authorize({
  cookieParser: cookieParser,
  key:          'connect.sid',
  secret:       secrets.sessionSecret,
  store:        store,
  success:      onAuthorizeSuccess,
  fail:         onAuthorizeFail,
}));

var socket_map = {};

function saveMessage (socket, data, thread_id, callback) {
    var newMsg = new Message({
        message: data.message,
        timeSent: new Date(),
        _thread: thread_id,
        _sender: socket.request.user._id,
    });
    newMsg.save(function (err) {
        if (err) {
            throw err;
        }
        callback(null, socket, data, thread_id, newMsg)
    });
}

function sendMessage (socket, data, thread_id, newMsg, callback) {
    var sender = socket.request.user;
    Thread.findOne({_id: thread_id})
    .populate('_participants')
    .exec(function (err, thread) {
        thread._participants.forEach(function (user) {
            var is_me = sender._id.toString() == user._id.toString();
            // if recipient is online, ping him the message via socket
            if (socket_map[user._id]) {
                io.to(socket_map[user._id]).emit('new message', {
                    message: newMsg.message,
                    timeSent: newMsg.timeSent,
                    thread: thread,
                    author: {
                        name: sender.profile.name,
                        pic: sender.profile.picture,
                        id: sender._id,
                        isMe: is_me,
                    },
                });
            }

        });
        callback(null);
    });
}

function saveThread (socket, data, unused_id, callback) {
    var newThread = new Thread({
        _participants: [socket.request.user._id].concat(data.to).sort(),
        lastUpdated: new Date(),
    });

    newThread.save(function (err) {
        callback(null, socket, data, newThread._id);
    });
}

io.sockets.on('connection', function (socket) {
    socket_map[socket.request.user._id] = socket.id;
    socket.on('send message', function (data) {
        var arr = [
            saveMessage,
            sendMessage,
        ];

        if (data.isNewThread) {
            arr.unshift(saveThread);
        }

        arr.unshift(function (callback) {
            callback(null, socket, data, data.thread_id);
        })

        async.waterfall(arr, function (err, results) {
            if (err) {
                console.log("Error: " + err);
            }
        });
    });
});

/**
 * Primary app routes.
 */
app.get('/', function (req, res) {
    if (req.isAuthenticated()) {
        userController.findUsers(req, res);
    } else {
        homeController.index(req, res);
    }
});
app.get('/privacy', homeController.privacy);
app.get('/newaccount', passportConf.isAuthenticated, function (req, res) {
  res.render('account/newaccount', {
    my_skills: [],
    my_interests: [],
    activities: activities.activityMap,
  })
});
app.post('/newaccount', userController.newAccount);
app.get('/about', homeController.about);
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', passportConfig.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConfig.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConfig.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConfig.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConfig.isAuthenticated, userController.getOauthUnlink);
app.get('/messages', passportConfig.isAuthenticated, messageController.showMessages);
app.get('/_threadMessages/:id', passportConfig.isAuthenticated, messageController.getMessages);
app.get('/profile/:id', passportConfig.isAuthenticated, userController.showProfile);

app.get('/transactions', passportConf.isAuthenticated, transactionController.showTransactions);
app.post('/transactions', passportConf.isAuthenticated, transactionController.postTransaction);

app.post('/location', passportConf.isAuthenticated, userController.postLocation);

/**
 * User routes
 */
app.get('/users', passportConf.isAuthenticated, userController.findUsers);
app.get('/users/list', userController.list);

/**
 * API examples routes.
 */
app.get('/api', apiController.getApi);
app.get('/api/facebook', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getFacebook);
app.get('/api/twitter', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getTwitter);
app.post('/api/twitter', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.postTwitter);

/**
 * OAuth authentication routes. (Sign in)
 */
app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'public_profile', 'user_location', 'user_hometown'] }));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), (req, res) => {
  res.redirect(req.session.returnTo || '/account');
});
app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' }));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => {
  res.redirect(req.session.returnTo || '/account');
});
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), (req, res) => {
  res.redirect(req.session.returnTo || '/account');
});

/**
 * Error Handler.
 */
if (app.settings.env === 'production') {
  app.use(function(req, res, next){
    // the status option, or res.statusCode = 404
    // are equivalent, however with the option we
    // get the "status" local available as well
    res.status(404).render('error/404', {
      status: 404,
      url: req.url,
    });
  });
  app.use(function(err, req, res, next){
    // we may use properties of the error object
    // here and next(err) appropriately, or if
    // we possibly recovered from the error, simply next().
    res.status(500).render('error/500', {
        status: err.status || 500,
        error: err,
    });
  });
} else {
  app.use(errorHandler());
}

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

module.exports = app;
<|endoftext|>


<commit_before>var gebo = require('./index')();

gebo.start();
<commit_msg>Remove old server entry point<commit_after><|endoftext|>


<commit_before>var express = require('express');
var app = express();
var newrelic = require('newrelic');
var helpers = require('./helpers');

var controllers = require('./controllers');

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));

app.get('/', controllers.system.home);
app.get('/articulo/:slug', controllers.system.article);
app.post('/hook', controllers.system.hook);

app.get('/rss', controllers.system.rss);

helpers.fs.setArticles( 'articles' );

app.listen(process.env.PORT || 5000);
<commit_msg>change post to get<commit_after>var express = require('express');
var app = express();
var newrelic = require('newrelic');
var helpers = require('./helpers');

var controllers = require('./controllers');

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));

app.get('/', controllers.system.home);
app.get('/articulo/:slug', controllers.system.article);
app.get('/hook', controllers.system.hook);

app.get('/rss', controllers.system.rss);

helpers.fs.setArticles( 'articles' );

app.listen(process.env.PORT || 5000);
<|endoftext|>


<commit_before>var tsl2591 = require('tsl2591');

/* Use /dev/i2c-0 on older Raspis */
/* Note the options are passed directly to the i2c module */
var light = new tsl2591({device: '/dev/i2c-1'});

module.exports = {};

module.exports.load = function () {
	return new Promise(function (resolve, reject) {
		light.init({AGAIN: 2, ATIME: 1}, function(err) {
			if (err) {
				reject(err);
			} else {
				console.log('TSL2591 ready');
				resolve();
			}
		});
	});
}

module.exports.getData = function () {
	return new Promise(function (resolve, reject) {
		light.readLuminosity(function(err, data) {
            if (err) {
                console.log(err);
            }
            else {
                console.log(data);
            }
            var raw = data.vis_ir;
            console.log(data.vis_ir);
        });
		resolve([
			{
				sensorID: 4,
				value: latestTemp,
				unit: "°C",
				measurement: "Temperature",
				location: "Soil",
				htmlDecimal: 1
			}
		]);
	});
}
<commit_msg>move to within promise<commit_after>var tsl2591 = require('tsl2591');

/* Use /dev/i2c-0 on older Raspis */
/* Note the options are passed directly to the i2c module */
var light = new tsl2591({device: '/dev/i2c-1'});

module.exports = {};

module.exports.load = function () {
	return new Promise(function (resolve, reject) {
		light.init({AGAIN: 2, ATIME: 1}, function(err) {
			if (err) {
				reject(err);
			} else {
				console.log('TSL2591 ready');
				resolve();
			}
		});
	});
}

module.exports.getData = function () {
	return new Promise(function (resolve, reject) {
		light.readLuminosity(function(err, data) {
            if (err) {
                reject(err);
            }
            else {
                console.log(data);
				resolve([
					{
						sensorID: 5,
						value: data.vis_ir,
						unit: "lux",
						measurement: "Light",
						location: "ICT office",
						htmlDecimal: 0
					}
				]);
            }
        });
	});
}
<|endoftext|>


<commit_before>var package = require('./package.json'),
    path    = require('path'),
    program = require('commander'),
    express = require('express'),
    iosys   = require('iosys'),
    aux     = require('./lib/aux'),
    render  = require('./lib/render'),
    git     = require('./lib/git')

function start(options) {
    var app = express(),
        finder = iosys.finder(options.repo, __dirname)

    app.disable('x-powered-by')
    app.use(express.logger('dev'))
    app.use(aux(finder))
    app.use(render(finder))

    var pub = '/files'
    app.use(pub, express.static(options.repo + pub))
    app.use(pub, express.static(__dirname + pub))

    if (options.nop) return app

    app.listen(options.port)
}

function cli() {
    program
        .option('-r, --repo <dir>', 'git repository to use',
                path.resolve, process.cwd())
        .option('-p, --port <num>', 'port to listen on',
                parseInt, 9000)
        .option('-N, --nop', 'do nothing')
        .version(package.version)
        .parse(process.argv)

    /* jshint expr: true */
    if (git.isRepo(program.repo))
        console.log('wat:', program.repo)
    else
        console.error('wat: err'), process.exit()

    start(program)
}

function main() { git.usable(cli) }

if (require.main === module) main()

module.exports.main = main
module.exports.start = start
<commit_msg>IP address to bind to<commit_after>var package = require('./package.json'),
    path    = require('path'),
    program = require('commander'),
    express = require('express'),
    iosys   = require('iosys'),
    aux     = require('./lib/aux'),
    render  = require('./lib/render'),
    git     = require('./lib/git')

function start(options) {
    var app = express(),
        finder = iosys.finder(options.repo, __dirname)

    app.disable('x-powered-by')
    app.use(express.logger('dev'))
    app.use(aux(finder))
    app.use(render(finder))

    var pub = '/files'
    app.use(pub, express.static(options.repo + pub))
    app.use(pub, express.static(__dirname + pub))

    if (options.nop) return app

    app.listen(options.port, options.bind)
}

function cli() {
    program
        .option('-r, --repo <dir>', 'git repository to use',
                path.resolve, process.cwd())
        .option('-p, --port <num>', 'port to listen on',
                parseInt, 9000)
        .option('-b, --bind <ip>', 'IP address to bind to',
                '0.0.0.0')
        .option('-N, --nop', 'do nothing')
        .version(package.version)
        .parse(process.argv)

    /* jshint expr: true */
    if (git.isRepo(program.repo))
        console.log('wat:', program.repo)
    else
        console.error('wat: err'), process.exit()

    start(program)
}

function main() { git.usable(cli) }

if (require.main === module) main()

module.exports.main = main
module.exports.start = start
<|endoftext|>


<commit_before>var express = require('express')
  , http = require('http')
  , path = require('path')
  , crypto = require('crypto')
  , routes = require('./routes')
  , db = require('./db')
  , auth = require('./auth')
  , util = require('./util')

var app = express();

app.configure(function(){
	// all environments
	app.set('port', process.env.PORT || 8080);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');

	app.use(express.cookieParser());
	app.use(express.logger('dev'));
	app.use(express.bodyParser({
		uploadDir: './public/uploads'
	}));
	app.use(express.methodOverride());
	app.use(util.verifyRecaptcha);
	app.use(function(req, res, next) {
		res.locals._nl2br_escape = util.nl2br_escape;
		res.locals._quote = util.quote;
		res.locals._isset = util.isset;
		res.locals._timeSince = util.timeSince;
		res.locals._attachment = util.attachment;
		res.locals._slug = util.slug;

		if (req.url.substring(0, 6) == '/ajax/') {
			req.url = req.url.substring(5);
			res.locals.__REQUEST_TYPE = 'ajax';
			res.locals.__REQUEST_URL = req.url;
		} else {
			res.locals.__REQUEST_TYPE = 'normal';
			res.locals.__REQUEST_URL = req.url;
		}
		next();
	});
	app.use(express.static(path.join(__dirname, 'public')));
	app.use(app.router);

	app.use(function(err, req, res, next) {
		if (!err) next();

		console.log(err);
		res.statusCode = 500;
		res.send("<script>notifybox(\"We're sorry, there was an error with your request. :(\");</script>");
	});
});

/// ROUTEWARE:
// auth.require - require authentication
// auth.build - build authentication
// util.prepareLayout - prepare layout (navbar, footer) if non-ajax request // todo consider placing this on everything
//////////////////////////////////////////////////////////////////////////////////////

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

// church fund
app.get('/fund', util.prepareLayout, routes.fund);

// grants page
app.get('/grants/:type?/:page?', util.prepareLayout, auth.build, routes.grants.show);
app.post('/grants', util.prepareLayout, routes.grants.submitgrant);

// blog system
app.post('/blog/:id/submitpost', auth.require, routes.blog.submitpost);
app.post('/blog/:id/setimage', auth.require, routes.blog.setimage);
app.get('/blog/:id/newpost', util.prepareLayout, auth.require, routes.blog.newpost);
app.get('/blog/:id/:page?', util.prepareLayout, auth.build, routes.blog.show);
app.get('/post/:id', util.prepareLayout, auth.build, routes.blogpost.show);
app.post('/post/:id/edit', auth.require, routes.blogpost.editpost);
app.post('/post/:id/delete', auth.require, routes.blogpost.deletepost);
app.get('/blogs', util.prepareLayout, routes.blog.list);

// TODO: make this safer, more agile
app.post('/uploadimage', auth.require, function(req, res) {
	if (!req.files.file)
		return util.error("File was not submitted.", req, res, "File was not submitted.");

	var file = req.files.file;

	var id = req.files.file.path.replace("public/uploads/", "");

	var oreturn = {path:"/uploads/" + id, id:id};

	res.send(JSON.stringify(oreturn));
});

app.get("*", util.prepareLayout, function(req, res) {
	res.statusCode = 404;
	res.render("404", {title:"404"});
})

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>Don't util.prepareLayout on missing assets.<commit_after>var express = require('express')
  , http = require('http')
  , path = require('path')
  , crypto = require('crypto')
  , routes = require('./routes')
  , db = require('./db')
  , auth = require('./auth')
  , util = require('./util')

var app = express();

app.configure(function(){
	// all environments
	app.set('port', process.env.PORT || 8080);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');

	app.use(express.cookieParser());
	app.use(express.logger('dev'));
	app.use(express.bodyParser({
		uploadDir: './public/uploads'
	}));
	app.use(express.methodOverride());
	app.use(util.verifyRecaptcha);
	app.use(function(req, res, next) {
		res.locals._nl2br_escape = util.nl2br_escape;
		res.locals._quote = util.quote;
		res.locals._isset = util.isset;
		res.locals._timeSince = util.timeSince;
		res.locals._attachment = util.attachment;
		res.locals._slug = util.slug;

		if (req.url.substring(0, 6) == '/ajax/') {
			req.url = req.url.substring(5);
			res.locals.__REQUEST_TYPE = 'ajax';
			res.locals.__REQUEST_URL = req.url;
		} else {
			res.locals.__REQUEST_TYPE = 'normal';
			res.locals.__REQUEST_URL = req.url;
		}
		next();
	});
	app.use(express.static(path.join(__dirname, 'public')));
	app.use(app.router);

	app.use(function(err, req, res, next) {
		if (!err) next();

		console.log(err);
		res.statusCode = 500;
		res.send("<script>notifybox(\"We're sorry, there was an error with your request. :(\");</script>");
	});
});

/// ROUTEWARE:
// auth.require - require authentication
// auth.build - build authentication
// util.prepareLayout - prepare layout (navbar, footer) if non-ajax request // todo consider placing this on everything
//////////////////////////////////////////////////////////////////////////////////////

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

// church fund
app.get('/fund', util.prepareLayout, routes.fund);

// grants page
app.get('/grants/:type?/:page?', util.prepareLayout, auth.build, routes.grants.show);
app.post('/grants', util.prepareLayout, routes.grants.submitgrant);

// blog system
app.post('/blog/:id/submitpost', auth.require, routes.blog.submitpost);
app.post('/blog/:id/setimage', auth.require, routes.blog.setimage);
app.get('/blog/:id/newpost', util.prepareLayout, auth.require, routes.blog.newpost);
app.get('/blog/:id/:page?', util.prepareLayout, auth.build, routes.blog.show);
app.get('/post/:id', util.prepareLayout, auth.build, routes.blogpost.show);
app.post('/post/:id/edit', auth.require, routes.blogpost.editpost);
app.post('/post/:id/delete', auth.require, routes.blogpost.deletepost);
app.get('/blogs', util.prepareLayout, routes.blog.list);

// TODO: make this safer, more agile
app.post('/uploadimage', auth.require, function(req, res) {
	if (!req.files.file)
		return util.error("File was not submitted.", req, res, "File was not submitted.");

	var file = req.files.file;

	var id = req.files.file.path.replace("public/uploads/", "");

	var oreturn = {path:"/uploads/" + id, id:id};

	res.send(JSON.stringify(oreturn));
});

app.get(/\.(gif|jpg|png|css|js)$/, function(req, res) {
	res.statusCode = 404;
	res.send("404 Not Found");
})

app.get("*", util.prepareLayout, function(req, res) {
	res.statusCode = 404;
	res.render("404", {title:"404"});
})

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


<commit_before>var application_root = __dirname,
    express = require("express"),
    path = require("path"),
    mongoose = require('mongoose'),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    morgan = require('morgan');

mongoose.Promise = require('bluebird');

var app = express();

// database
console.log("Connecting to db... " + process.env.MONGO);
mongoose.connect(process.env.MONGO);

// config
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.static(path.join(application_root, "public")));
app.use(clientErrorHandler);
app.use(errorHandler);
app.use(morgan('combined'));

var Schema = mongoose.Schema; //Schema.ObjectId

// Schemas

var Advisors = new Schema({
    name: { type: String, required: [true, "Must have a name"] },
    status: {
        type: String,
        required: [true, "Must have a status"],
        enum: ["Busy", "Available", "Unavailable"] ,
        default: "Unavailable"
      },
    turnOverRate: { type: Number },
    avgPerHour: { type: Number },
    modified: { type: Date, default: Date.now }
});

var AdvisorModel = mongoose.model('Advisor', Advisors);

var CourseCatalogModel = mongoose.model('CourseCatalog', new Schema({
  title: String,
  desc: String
}), 'course_catalog');

var Students = new Schema({
    name: {
      type: String,
      required: [true, "Must have a student name"],
      min: 2,
      max: 50
    },
    phoneNumber: {
      type: Number,
      validate: function(phoneNumber) { return phoneNumber.length == 10 }
    },
    studenId: { type: Number, required: [true, "Student ID is required"] },
    modified: { type: Date, default: Date.now }
});

// Appointment Model
var Appointment = new Schema({
    description: {
      type: String,
      required: [true, 'Description required'],
      min: 5,
      max: 100
    },
    student: [Students],
    advisorId: {
      type: String,
      required: [true, 'Advisor required for appointment'],
      validate: {
          validator: function(advisorId) {
            var promise = AdvisorModel.findById(advisorId).exec();
            promise.then(function(advisor) {
              return advisor.status == 'Available' || advisor.satus == 'Busy';
            })
            .catch(function(err) {
              return false;
           })},
          message : '{VALUE} is not a valid advisor!'
        }
    },
    state: {
      type: String,
      enum: ['Waiting', 'In Progress', 'Done'],
      default: 'Waiting',
    },
    type: {
        type: String,
        enum: ['Advising', 'Drop', 'Other'],
        required: 'Wrong Appointment Type or No appointment Type'
    },
    extraInfo: { type: String },
    position: { type: Number, default: -1 },
    modified: { type: Date, default: Date.now }
});

var AppointmentModel = mongoose.model('Appointment', Appointment);

/* Appointment Document
{
  "description": "I need to DROP",
  "type": "Drop",
  "student": [{
    "name": "Leeroy Jenkins",
    "studenId": 10005959
  }],
  "advisorId" : "5833af88321f5f26ccd9231b",
  "extraInfo": "Hey, where is Dr. Beckers office?"
  "state": "Waiting" ( optional or for updates)
}
*/

/* Advisor Document
    {
        "name": "Barach",
        "status": "Busy"
    }
*/

// Queue stuff
console.log("Initializing queue...");
var queue = [];

var promise = AppointmentModel.find().exec()

promise.then(function(appointment) {
  console.log("Saved queue");
  console.log(appointment);
  for(var i = 0; i < appointment.length; i++) {
    if(appointment.state !== "Done") {
      var pos = appointment[i].position;
      queue[pos] = appointment[i];
    }
  }
})
.catch(function(err) {
  console.log(err);
  console.log("Could not recover stored state");
});

function dequeue_app(idx) {
  if(queue.length == 1) {
    queue = [];
  }
  else {
    for(var i = idx; i < queue.length - 1; i++) {
      queue[i] = queue[i + 1];
      queue[i].position = i;
    }
  }
}

// function move(to_pos, from_pos) {
//   if(idx < 0) return;
//   for(var i = to_pos; i < queue.length; i++) {
//     var temp = queue[to_pos];
//     queue[to_pos] = queue[from_pos];

//   }
// }

// REST api

app.get('/api', function (req, res) {
  res.send('Kiosk API is running');
});

// POST to CREATE
app.post('/api/appointments', function (req, res) {
  var appointment = new AppointmentModel({
    description: req.body.description,
    student: req.body.student,
    advisorId: req.body.advisorId,
    type: req.body.type,
    extraInfo: req.body.extraInfo,
    position: queue.length
  });

  appointment.save(function (err) {
    if (!err) {
      queue.push(appointment);
      console.log("Place in queue");
      console.log(queue[queue.length - 1].position)
      return res.send(appointment)
    } else {
      return res.send(err)
    }
  });
});

// PUT to UPDATE

// Bulk update
// app.put('/api/appointments', function (req, res) {
//     var i, len = 0;
//     console.log("is Array req.body.appointment");
//     console.log(Array.isArray(req.body.appointment));
//     console.log("PUT: (appointment)");
//     console.log(req.body.appointment);
//     if (Array.isArray(req.body.appointment)) {
//         len = req.body.appointment.length;
//     }
//     for (i = 0; i < len; i++) {
//         console.log("UPDATE appointment by id:");
//         for (var id in req.body.appointment[i]) {
//             console.log(id);
//         }
//         AppointmentModel.update({ "_id": id }, req.body.appointment[i][id], function (err, numAffected) {
//             if (err) {
//                 console.log("Error on update");
//                 console.log(err);
//                 return res.send(err);
//             } else {
//                 console.log("updated num: " + numAffected);
//                 return res.send(req.body.appointment)
//             }
//         });
//     }
// });

// Single update
app.put('/api/appointments/:id', function (req, res) {
  return AppointmentModel.findById(req.params.id, function (err, appointment) {
    appointment.description = req.body.description;
    appointment.student = req.body.student;
    appointment.advisor = req.body.advisor;
    appointment.type = req.body.type;
    appointment.extraInfo = req.body.extraInfo;
    return appointment.save(function (err) {
      if (!err) {
        console.log("updated");
        queue[appointment.position] = appointment;
        return res.send(appointment);
      } else {
        console.log(err);
        return res.send(err);
      }
    });
  });
});

// Update Appointment state
app.put('/api/appointments/:id/state', function (req, res) {
  return AppointmentModel.findById(req.params.id, function (err, appointment) {
    appointment.state = req.body.state;
    return appointment.save(function (err) {
      if (!err) {
        console.log("updated");
        queue[appointment.position] = appointment;
        return res.send(appointment);
      } else {
        console.log(err);
        return res.send(err);
      }
    });
  });
});

// GET to READ

// List appointment
app.get('/api/appointments', function (req, res) {
  return res.send(queue);
});

// Single appointment
app.get('/api/appointments/:id', function (req, res) {
  return AppointmentModel.findById(req.params.id, function (err, appointment) {
    if (!err) {
      return res.send(appointment);
    } else {
      return res.send(err);
    }
  });
});

// DELETE to DESTROY

// Bulk destroy all appointment
app.delete('/api/appointments', function (req, res) {
  AppointmentModel.remove(function (err) {
    if (!err) {
      console.log("removed");
      queue = [];
      return res.send(queue);
    } else {
      return res.send(err);
    }
  });
});

// remove a single appointment
app.delete('/api/appointments/:id', function (req, res) {
  return AppointmentModel.findById(req.params.id, function (err, appointment) {
    return appointment.remove(function (err) {
      if (!err) {
        dequeue_app(appointment.position);
        console.log("removed");
        return res.send('');
      } else {
        return res.send(err);
      }
    });
  });
});

// Get next up
app.get('/api/appointments/next', function (req, res) {
  console.log(queue[0])
  return res.send(queue[0]);
});

// Remove next up
app.delete('/api/appointments/next', function (req, res) {
  console.log('Removing -->' + queue[0]._id)
  var promise = AppointmentModel.findById(queue[0].id).exec();
  promise.then(function(appointment) {
    return appointment.remove()
  })
  .then(function(appointment) {
    console.log("dequeuing")
    dequeue_app();
    res.send(queue)
  })
  .catch(function(err) {
    console.log(err);
  })
});

// Add Advisor
app.post('/api/advisors', function (req, res) {
  var advisor;
  console.log("POST: ");
  console.log(req.body);
  advisor = new AdvisorModel({
    name: req.body.name,
    status: req.body.status
  });
  advisor.save(function (err) {
    if (!err) {
      console.log("created");
      return res.send(advisor);
    } else {
      console.log(err);
      return res.send(err);
    }
  });
});

// Update Advisor
app.put('/api/advisors/:id', function (req, res) {
  var promise = AdvisorModel.findById(req.params.id).exec();
  promise.then(function(advisor) {
    advisor.name = req.body.name
    advisor.status = req.body.status;
    return advisor.save();
  })
  .then(function(advisor) {
    console.log("Advisor Saved!");
    return res.send(advisor);
  })
  .catch(function(err) {
    console.log(err);
    return res.send(err);
  })
});

// Update Advisor Status
app.put('/api/advisors/:id/status', function (req, res) {
  var promise = AdvisorModel.findById(req.params.id).exec();
  promise.then(function(advisor) {
    advisor.status = req.body.status;
    return advisor.save();
  })
  .then(function(advisor) {
    console.log("Advisor Updated!");
    return res.send(advisor);
  })
  .catch(function(err) {
    console.log(err);
    return res.send(err);
  })
});

// Get Advisors
app.get('/api/advisors', function (req, res) {
 return AdvisorModel.find(function (err, advisors) {
    if (!err) {
      console.log("Getting Advisors");
      return res.send(advisors);
    } else {
      console.log(err);
      return res.send(err);
    }
  });
});

// Get Advisor by id
app.get('/api/advisors/:id', function (req, res) {
   return AdvisorModel.findById(req.params.id, function (err, advisor) {
    if (!err) {
      return res.send(advisor);
    } else {
      console.log(err);
      return res.send(err);
    }
  });
})

// Delete Advsior
app.delete('/api/advisors/:id', function (req, res) {
  return AdvisorModel.findById(req.params.id, function (err, advisor) {
    return advisor.remove(function (err) {
      if (!err) {
        console.log("removed");
        return res.send('');
      } else {
        console.log(err);
        return res.send(err);
      }
    });
  });
});

/* -- Course Catalog --  */
app.get('/api/courses', (req, res) => {
  CourseCatalogModel.find().then(courses => {
    return res.send(courses);
  })
});

function clientErrorHandler (err, req, res, next) {
  if (req.xhr) {
    res.status(500).send({ error: 'Something failed!' })
  } else {
    next(err)
  }
}

function errorHandler (err, req, res, next) {
  res.status(500)
  res.render('error', { error: err })
}

// launch server
app.listen(4242);
console.log("Listening on 4242...");
<commit_msg>Fixed some stuff to upload appointments<commit_after>var application_root = __dirname,
    express = require("express"),
    path = require("path"),
    mongoose = require('mongoose'),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    morgan = require('morgan');

mongoose.Promise = require('bluebird');

var app = express();

// database
console.log("Connecting to db... " + process.env.MONGO);
mongoose.connect(process.env.MONGO);

// config
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.static(path.join(application_root, "public")));
app.use(clientErrorHandler);
app.use(errorHandler);
app.use(morgan('combined'));

var Schema = mongoose.Schema; //Schema.ObjectId

// Schemas

var Advisors = new Schema({
    name: { type: String, required: [true, "Must have a name"] },
    status: {
        type: String,
        required: [true, "Must have a status"],
        enum: ["Busy", "Available", "Unavailable"] ,
        default: "Unavailable"
      },
    turnOverRate: { type: Number },
    avgPerHour: { type: Number },
    modified: { type: Date, default: Date.now }
});

var AdvisorModel = mongoose.model('Advisor', Advisors);

var CourseCatalogModel = mongoose.model('CourseCatalog', new Schema({
  title: String,
  desc: String
}), 'course_catalog');

var Students = new Schema({
    name: {
      type: String,
      required: [true, "Must have a student name"],
      min: 2,
      max: 50
    },
    phoneNumber: Number,
    studentId: { type: Number, required: [true, "Student ID is required"] },
    modified: { type: Date, default: Date.now }
});

// Appointment Model
var Appointment = new Schema({
    description: {
      type: String,
      required: [true, 'Description required'],
      min: 5,
      max: 100
    },
    student: [Students],
    advisorId: {
      type: String,
      validate: {
          validator: function(advisorId) {
            var promise = AdvisorModel.findById(advisorId).exec();
            promise.then(function(advisor) {
              return advisor.status == 'Available' || advisor.satus == 'Busy';
            })
            .catch(function(err) {
              return false;
           })},
          message : '{VALUE} is not a valid advisor!'
        }
    },
    state: {
      type: String,
      enum: ['Waiting', 'In Progress', 'Done'],
      default: 'Waiting',
    },
    type: {
        type: String,
        enum: ['Advising', 'Drop', 'Other'],
        required: 'Wrong Appointment Type or No appointment Type'
    },
    extraInfo: { type: String },
    position: { type: Number, default: -1 },
    modified: { type: Date, default: Date.now }
});

var AppointmentModel = mongoose.model('Appointment', Appointment);

/* Appointment Document
{
  "description": "I need to DROP",
  "type": "Drop",
  "student": [{
    "name": "Leeroy Jenkins",
    "studenId": 10005959
  }],
  "advisorId" : "5833af88321f5f26ccd9231b",
  "extraInfo": "Hey, where is Dr. Beckers office?"
  "state": "Waiting" ( optional or for updates)
}
*/

/* Advisor Document
    {
        "name": "Barach",
        "status": "Busy"
    }
*/

// Queue stuff
console.log("Initializing queue...");
var queue = [];

var promise = AppointmentModel.find().exec()

promise.then(function(appointment) {
  console.log("Saved queue");
  console.log(appointment);
  for(var i = 0; i < appointment.length; i++) {
    if(appointment.state !== "Done") {
      var pos = appointment[i].position;
      queue[pos] = appointment[i];
    }
  }
})
.catch(function(err) {
  console.log(err);
  console.log("Could not recover stored state");
});

function dequeue_app(idx) {
  if(queue.length == 1) {
    queue = [];
  }
  else {
    for(var i = idx; i < queue.length - 1; i++) {
      queue[i] = queue[i + 1];
      queue[i].position = i;
    }
  }
}

// function move(to_pos, from_pos) {
//   if(idx < 0) return;
//   for(var i = to_pos; i < queue.length; i++) {
//     var temp = queue[to_pos];
//     queue[to_pos] = queue[from_pos];

//   }
// }

// REST api

app.get('/api', function (req, res) {
  res.send('Kiosk API is running');
});

// POST to CREATE
app.post('/api/appointments', function (req, res) {
  console.log('creating appointment');
  console.log(req.body);
  var appointment = new AppointmentModel({
    description: req.body.description,
    student: [req.body.student],
    advisorId: req.body.advisorId,
    type: req.body.type,
    extraInfo: req.body.extraInfo,
    position: queue.length
  });

  appointment.save(function (err) {
    if (!err) {
      queue.push(appointment);
      console.log("Place in queue");
      console.log(queue[queue.length - 1].position)
      return res.send(appointment)
    } else {
      return res.status(400).send(err)
    }
  });
});

// PUT to UPDATE

// Bulk update
// app.put('/api/appointments', function (req, res) {
//     var i, len = 0;
//     console.log("is Array req.body.appointment");
//     console.log(Array.isArray(req.body.appointment));
//     console.log("PUT: (appointment)");
//     console.log(req.body.appointment);
//     if (Array.isArray(req.body.appointment)) {
//         len = req.body.appointment.length;
//     }
//     for (i = 0; i < len; i++) {
//         console.log("UPDATE appointment by id:");
//         for (var id in req.body.appointment[i]) {
//             console.log(id);
//         }
//         AppointmentModel.update({ "_id": id }, req.body.appointment[i][id], function (err, numAffected) {
//             if (err) {
//                 console.log("Error on update");
//                 console.log(err);
//                 return res.send(err);
//             } else {
//                 console.log("updated num: " + numAffected);
//                 return res.send(req.body.appointment)
//             }
//         });
//     }
// });

// Single update
app.put('/api/appointments/:id', function (req, res) {
  return AppointmentModel.findById(req.params.id, function (err, appointment) {
    appointment.description = req.body.description;
    appointment.student = req.body.student;
    appointment.advisor = req.body.advisor;
    appointment.type = req.body.type;
    appointment.extraInfo = req.body.extraInfo;
    return appointment.save(function (err) {
      if (!err) {
        console.log("updated");
        queue[appointment.position] = appointment;
        return res.send(appointment);
      } else {
        console.log(err);
        return res.send(err);
      }
    });
  });
});

// Update Appointment state
app.put('/api/appointments/:id/state', function (req, res) {
  return AppointmentModel.findById(req.params.id, function (err, appointment) {
    appointment.state = req.body.state;
    return appointment.save(function (err) {
      if (!err) {
        console.log("updated");
        queue[appointment.position] = appointment;
        return res.send(appointment);
      } else {
        console.log(err);
        return res.send(err);
      }
    });
  });
});

// GET to READ

// List appointment
app.get('/api/appointments', function (req, res) {
  AppointmentModel.find({state: { $ne: 'Done' }})
    .then(apps => {
      return res.send(apps);
    })
});

// Single appointment
app.get('/api/appointments/:id', function (req, res) {
  return AppointmentModel.findById(req.params.id, function (err, appointment) {
    if (!err) {
      return res.send(appointment);
    } else {
      return res.send(err);
    }
  });
});

// DELETE to DESTROY

// Bulk destroy all appointment
app.delete('/api/appointments', function (req, res) {
  AppointmentModel.remove(function (err) {
    if (!err) {
      console.log("removed");
      queue = [];
      return res.send(queue);
    } else {
      return res.send(err);
    }
  });
});

// remove a single appointment
app.delete('/api/appointments/:id', function (req, res) {
  return AppointmentModel.findById(req.params.id, function (err, appointment) {
    return appointment.remove(function (err) {
      if (!err) {
        dequeue_app(appointment.position);
        console.log("removed");
        return res.send('');
      } else {
        return res.send(err);
      }
    });
  });
});

// Get next up
app.get('/api/appointments/next', function (req, res) {
  console.log(queue[0])
  return res.send(queue[0]);
});

// Remove next up
app.delete('/api/appointments/next', function (req, res) {
  console.log('Removing -->' + queue[0]._id)
  var promise = AppointmentModel.findById(queue[0].id).exec();
  promise.then(function(appointment) {
    return appointment.remove()
  })
  .then(function(appointment) {
    console.log("dequeuing")
    dequeue_app();
    res.send(queue)
  })
  .catch(function(err) {
    console.log(err);
  })
});

// Add Advisor
app.post('/api/advisors', function (req, res) {
  var advisor;
  console.log("POST: ");
  console.log(req.body);
  advisor = new AdvisorModel({
    name: req.body.name,
    status: req.body.status
  });
  advisor.save(function (err) {
    if (!err) {
      console.log("created");
      return res.send(advisor);
    } else {
      console.log(err);
      return res.send(err);
    }
  });
});

// Update Advisor
app.put('/api/advisors/:id', function (req, res) {
  var promise = AdvisorModel.findById(req.params.id).exec();
  promise.then(function(advisor) {
    advisor.name = req.body.name
    advisor.status = req.body.status;
    return advisor.save();
  })
  .then(function(advisor) {
    console.log("Advisor Saved!");
    return res.send(advisor);
  })
  .catch(function(err) {
    console.log(err);
    return res.send(err);
  })
});

// Update Advisor Status
app.put('/api/advisors/:id/status', function (req, res) {
  var promise = AdvisorModel.findById(req.params.id).exec();
  promise.then(function(advisor) {
    advisor.status = req.body.status;
    return advisor.save();
  })
  .then(function(advisor) {
    console.log("Advisor Updated!");
    return res.send(advisor);
  })
  .catch(function(err) {
    console.log(err);
    return res.send(err);
  })
});

// Get Advisors
app.get('/api/advisors', function (req, res) {
 return AdvisorModel.find(function (err, advisors) {
    if (!err) {
      console.log("Getting Advisors");
      return res.send(advisors);
    } else {
      console.log(err);
      return res.send(err);
    }
  });
});

// Get Advisor by id
app.get('/api/advisors/:id', function (req, res) {
   return AdvisorModel.findById(req.params.id, function (err, advisor) {
    if (!err) {
      return res.send(advisor);
    } else {
      console.log(err);
      return res.send(err);
    }
  });
})

// Delete Advsior
app.delete('/api/advisors/:id', function (req, res) {
  return AdvisorModel.findById(req.params.id, function (err, advisor) {
    return advisor.remove(function (err) {
      if (!err) {
        console.log("removed");
        return res.send('');
      } else {
        console.log(err);
        return res.send(err);
      }
    });
  });
});

/* -- Course Catalog --  */
app.get('/api/courses', (req, res) => {
  CourseCatalogModel.find().then(courses => {
    return res.send(courses);
  })
});

function clientErrorHandler (err, req, res, next) {
  if (req.xhr) {
    res.status(500).send({ error: 'Something failed!' })
  } else {
    next(err)
  }
}

function errorHandler (err, req, res, next) {
  res.status(500)
  res.render('error', { error: err })
}

// launch server
app.listen(4242);
console.log("Listening on 4242...");
<|endoftext|>


<commit_before>var test = require('tape');
var MoedCore = require('../..');

test('handling a key with an exact match executes the right function', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		target: function () {
			t.pass('mapping routed through');
		}
	});

	i.map('<b>', 'normal', 'command', {
		target: function () {
			t.fail('mapping routed through when it should not');
		}
	});

	i.fire('<w>');
});

test('sending one key when there are other potential matches does not execute', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		target: function () {
			t.fail('<w> should not execute, it is ambiguous');
		}
	});

	i.map('<w><b>', 'normal', 'command', {
		target: function () {
			t.pass('<w><b> should execute, it is an exact match');
		}
	});

	i.map('<b>', 'normal', 'command', {
		target: function () {
			t.fail('<b> should not execute, <b> is never used at the start of the combo');
		}
	});

	i.fire('<w>');
	i.fire('<b>');
});

test('passing a count before a command will execute it with that count', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		target: function (count) {
			t.strictEqual(count, 105, 'the mapping was executed with the correct count');
		}
	});

	i.fire('1');
	i.fire('0');
	i.fire('5');
	i.fire('<w>');
});

test('passing a count to a mapping that does not take one will not execute', function (t) {
	t.plan(0);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		acceptsCount: false,
		target: function () {
			t.fail('execute mapping that does not take a count, should not have');
		}
	});

	i.map('<b>', 'normal', 'command', {
		target: function () {
			t.fail('despite accepting a count, this should not have been executed');
		}
	});

	i.fire('1');
	i.fire('0');
	i.fire('<w>');
	t.end();
});

test('a command can be given another command', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;
	var target = 'from <w> with love';
	var result;

	i.map('<d>', 'normal', 'command', {
		acceptsMapping: 'motion',
		target: function (count, next) {
			result = next();
		}
	});

	i.map('<w>', 'normal', 'motion', {
		target: function () {
			return target;
		}
	});

	i.fire('<d>');
	i.fire('<w>');
	t.strictEqual(result, target, '<d> was passed the correct partially applied function');
});

test('a command can be given another command even when ambiguous', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;
	var target = 'from <w> with love';
	var result;

	i.map('<d>', 'normal', 'command', {
		acceptsMapping: 'motion',
		target: function (count, next) {
			result = next();
		}
	});

	i.map('<d><d>', 'normal', 'command', {
		target: function () {
			t.fail('should not execute');
		}
	});

	i.map('<w>', 'normal', 'motion', {
		target: function () {
			return target;
		}
	});

	i.fire('<d>');
	i.fire('<w>');
	t.strictEqual(result, target, '<d> was passed the correct partially applied function');
});
<commit_msg>Tested combos with counts.<commit_after>var test = require('tape');
var MoedCore = require('../..');

test('handling a key with an exact match executes the right function', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		target: function () {
			t.pass('mapping routed through');
		}
	});

	i.map('<b>', 'normal', 'command', {
		target: function () {
			t.fail('mapping routed through when it should not');
		}
	});

	i.fire('<w>');
});

test('sending one key when there are other potential matches does not execute', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		target: function () {
			t.fail('<w> should not execute, it is ambiguous');
		}
	});

	i.map('<w><b>', 'normal', 'command', {
		target: function () {
			t.pass('<w><b> should execute, it is an exact match');
		}
	});

	i.map('<b>', 'normal', 'command', {
		target: function () {
			t.fail('<b> should not execute, <b> is never used at the start of the combo');
		}
	});

	i.fire('<w>');
	i.fire('<b>');
});

test('passing a count before a command will execute it with that count', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		target: function (count) {
			t.strictEqual(count, 105, 'the mapping was executed with the correct count');
		}
	});

	i.fire('1');
	i.fire('0');
	i.fire('5');
	i.fire('<w>');
});

test('passing a count to a mapping that does not take one will not execute', function (t) {
	t.plan(0);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		acceptsCount: false,
		target: function () {
			t.fail('execute mapping that does not take a count, should not have');
		}
	});

	i.map('<b>', 'normal', 'command', {
		target: function () {
			t.fail('despite accepting a count, this should not have been executed');
		}
	});

	i.fire('1');
	i.fire('0');
	i.fire('<w>');
	t.end();
});

test('a command can be given another command', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;
	var target = 'from <w> with love';
	var result;

	i.map('<d>', 'normal', 'command', {
		acceptsMapping: 'motion',
		target: function (count, next) {
			result = next();
		}
	});

	i.map('<w>', 'normal', 'motion', {
		target: function () {
			return target;
		}
	});

	i.fire('<d>');
	i.fire('<w>');
	t.strictEqual(result, target, '<d> was passed the correct partially applied function');
});

test('a command can be given another command even when ambiguous', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;
	var target = 'from <w> with love';
	var result;

	i.map('<d>', 'normal', 'command', {
		acceptsMapping: 'motion',
		target: function (count, next) {
			result = next();
		}
	});

	i.map('<d><d>', 'normal', 'command', {
		target: function () {
			t.fail('should not execute');
		}
	});

	i.map('<w>', 'normal', 'motion', {
		target: function () {
			return target;
		}
	});

	i.fire('<d>');
	i.fire('<w>');
	t.strictEqual(result, target, '<d> was passed the correct partially applied function');
});

test('a command can be given another command with counts', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;
	var result;

	i.map('<d>', 'normal', 'command', {
		acceptsCount: true,
		acceptsMapping: 'motion',
		target: function (count, next) {
			result = count + next();
		}
	});

	i.map('<w>', 'normal', 'motion', {
		acceptsCount: true,
		target: function (count) {
			return count;
		}
	});

	i.fire('1');
	i.fire('0');
	i.fire('<d>');
	i.fire('2');
	i.fire('0');
	i.fire('<w>');
	t.strictEqual(result, 30, 'got the combined count');
});
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
const express = require('express');
const compression = require('compression');
const session = require('express-session');
const bodyParser = require('body-parser');
const logger = require('morgan');
const chalk = require('chalk');
const errorHandler = require('errorhandler');
const lusca = require('lusca');
const dotenv = require('dotenv');
const MongoStore = require('connect-mongo')(session);
const flash = require('express-flash');
const path = require('path');
const mongoose = require('mongoose');
const passport = require('passport');
const expressValidator = require('express-validator');
const expressStatusMonitor = require('express-status-monitor');
const sass = require('node-sass-middleware');
const multer = require('multer');

const upload = multer({ dest: path.join(__dirname, 'uploads') });

/**
 * Load environment variables from .env file, where API keys and passwords are configured.
 */
dotenv.load({ path: '.env' });

const bot = require('./bots/bot');
bot.start();

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

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

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

/**
 * Connect to MongoDB.
 */
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', () => {
  console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗'));
  process.exit();
});

/**
 * Express configuration.
 */
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(expressStatusMonitor());
app.use(compression());
app.use(sass({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public')
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: process.env.SESSION_SECRET,
  store: new MongoStore({
    url: process.env.MONGODB_URI || process.env.MONGOLAB_URI,
    autoReconnect: true
  })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
  if (req.path === '/api/upload') {
    next();
  } else {
    lusca.csrf()(req, res, next);
  }
});
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use((req, res, next) => {
  res.locals.user = req.user;
  next();
});
app.use((req, res, next) => {
  // After successful login, redirect back to the intended page
  if (!req.user &&
      req.path !== '/login' &&
      req.path !== '/signup' &&
      !req.path.match(/^\/auth/) &&
      !req.path.match(/\./)) {
    req.session.returnTo = req.path;
  } else if (req.user &&
      req.path == '/account') {
    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('/contact', contactController.getContact);
app.post('/contact', contactController.postContact);
app.get('/account', passportConfig.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConfig.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConfig.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConfig.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConfig.isAuthenticated, userController.getOauthUnlink);
app.get('/bot', passportConfig.isAuthenticated, botController.index);
app.post('/bot', passportConfig.isAuthenticated, botController.postSettings);

/**
 * 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', passportConfig.isAuthenticated, passportConfig.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', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getFoursquare);
app.get('/api/tumblr', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getTumblr);
app.get('/api/facebook', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getFacebook);
app.get('/api/github', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getGithub);
app.get('/api/twitter', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getTwitter);
app.post('/api/twitter', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.postTwitter);
app.get('/api/linkedin', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getLinkedin);
app.get('/api/instagram', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getInstagram);
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/upload', apiController.getFileUpload);
app.post('/api/upload', upload.single('myFile'), apiController.postFileUpload);
app.get('/api/pinterest', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getPinterest);
app.post('/api/pinterest', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.postPinterest);
app.get('/api/google-maps', apiController.getGoogleMaps);

/**
 * OAuth authentication routes. (Sign in)
 */
app.get('/auth/instagram', passport.authenticate('instagram'));
app.get('/auth/instagram/callback', passport.authenticate('instagram', { failureRedirect: '/login' }), (req, res) => {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'public_profile'] }));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), (req, res) => {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), (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' }), (req, res) => {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), (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' }), (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' }), (req, res) => {
  res.redirect('/api/foursquare');
});
app.get('/auth/tumblr', passport.authorize('tumblr'));
app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), (req, res) => {
  res.redirect('/api/tumblr');
});
app.get('/auth/steam', passport.authorize('openid', { state: 'SOME STATE' }));
app.get('/auth/steam/callback', passport.authorize('openid', { failureRedirect: '/login' }), (req, res) => {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/pinterest', passport.authorize('pinterest', { scope: 'read_public write_public' }));
app.get('/auth/pinterest/callback', passport.authorize('pinterest', { failureRedirect: '/login' }), (req, res) => {
  res.redirect('/api/pinterest');
});

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

/**
 * Start Express server.
 */
app.listen(app.get('port'), () => {
  console.log('%s App is running at http://localhost:%d in %s mode', chalk.green('✓'), app.get('port'), app.get('env'));

  console.log('  Press CTRL-C to stop\n');
});

module.exports = app;
<commit_msg>Remove unused APIs<commit_after>/**
 * Module dependencies.
 */
const express = require('express');
const compression = require('compression');
const session = require('express-session');
const bodyParser = require('body-parser');
const logger = require('morgan');
const chalk = require('chalk');
const errorHandler = require('errorhandler');
const lusca = require('lusca');
const dotenv = require('dotenv');
const MongoStore = require('connect-mongo')(session);
const flash = require('express-flash');
const path = require('path');
const mongoose = require('mongoose');
const passport = require('passport');
const expressValidator = require('express-validator');
const expressStatusMonitor = require('express-status-monitor');
const sass = require('node-sass-middleware');
const multer = require('multer');

const upload = multer({ dest: path.join(__dirname, 'uploads') });

/**
 * Load environment variables from .env file, where API keys and passwords are configured.
 */
dotenv.load({ path: '.env' });

const bot = require('./bots/bot');
bot.start();

/**
 * Controllers (route handlers).
 */
const homeController = require('./controllers/home');
const userController = require('./controllers/user');
const contactController = require('./controllers/contact');
const botController = require('./controllers/bot');

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

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

/**
 * Connect to MongoDB.
 */
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', () => {
  console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗'));
  process.exit();
});

/**
 * Express configuration.
 */
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(expressStatusMonitor());
app.use(compression());
app.use(sass({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public')
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: process.env.SESSION_SECRET,
  store: new MongoStore({
    url: process.env.MONGODB_URI || process.env.MONGOLAB_URI,
    autoReconnect: true
  })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
  if (req.path === '/api/upload') {
    next();
  } else {
    lusca.csrf()(req, res, next);
  }
});
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use((req, res, next) => {
  res.locals.user = req.user;
  next();
});
app.use((req, res, next) => {
  // After successful login, redirect back to the intended page
  if (!req.user &&
      req.path !== '/login' &&
      req.path !== '/signup' &&
      !req.path.match(/^\/auth/) &&
      !req.path.match(/\./)) {
    req.session.returnTo = req.path;
  } else if (req.user &&
      req.path == '/account') {
    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('/contact', contactController.getContact);
app.post('/contact', contactController.postContact);
app.get('/account', passportConfig.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConfig.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConfig.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConfig.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConfig.isAuthenticated, userController.getOauthUnlink);
app.get('/bot', passportConfig.isAuthenticated, botController.index);
app.post('/bot', passportConfig.isAuthenticated, botController.postSettings);

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

/**
 * Start Express server.
 */
app.listen(app.get('port'), () => {
  console.log('%s App is running at http://localhost:%d in %s mode', chalk.green('✓'), app.get('port'), app.get('env'));

  console.log('  Press CTRL-C to stop\n');
});

module.exports = app;
<|endoftext|>


<commit_before>var test = require('tape');
var MoedCore = require('../..');

test('handling a key with an exact match executes the right function', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		target: function () {
			t.pass('mapping routed through');
		}
	});

	i.map('<b>', 'normal', 'command', {
		target: function () {
			t.fail('mapping routed through when it should not');
		}
	});

	i.fire('<w>');
});

test('sending one key when there are other potential matches does not execute', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		target: function () {
			t.fail('<w> should not execute, it is ambiguous');
		}
	});

	i.map('<w><b>', 'normal', 'command', {
		target: function () {
			t.pass('<w><b> should execute, it is an exact match');
		}
	});

	i.map('<b>', 'normal', 'command', {
		target: function () {
			t.fail('<b> should not execute, <b> is never used at the start of the combo');
		}
	});

	i.fire('<w>');
	i.fire('<b>');
});

test('passing a count before a command will execute it that many times', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;
	var count = 0;

	i.map('<w>', 'normal', 'command', {
		target: function () {
			count++;
		}
	});

	i.fire('1');
	i.fire('0');
	i.fire('<w>');

	t.strictEqual(count, 10, 'the mapping was executed n times');
});

test('passing a count to a mapping tha does not take one will not execute', function (t) {
	t.plan(0);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		acceptsCount: false,
		target: function () {
			t.fail('execute mapping that does not take a count, should not have');
		}
	});

	i.map('<b>', 'normal', 'command', {
		target: function () {
			t.fail('despite accepting a count, this should not have been executed');
		}
	});

	i.fire('1');
	i.fire('0');
	i.fire('<w>');
	t.end();
});
<commit_msg>Now testing for a number being passed.<commit_after>var test = require('tape');
var MoedCore = require('../..');

test('handling a key with an exact match executes the right function', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		target: function () {
			t.pass('mapping routed through');
		}
	});

	i.map('<b>', 'normal', 'command', {
		target: function () {
			t.fail('mapping routed through when it should not');
		}
	});

	i.fire('<w>');
});

test('sending one key when there are other potential matches does not execute', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		target: function () {
			t.fail('<w> should not execute, it is ambiguous');
		}
	});

	i.map('<w><b>', 'normal', 'command', {
		target: function () {
			t.pass('<w><b> should execute, it is an exact match');
		}
	});

	i.map('<b>', 'normal', 'command', {
		target: function () {
			t.fail('<b> should not execute, <b> is never used at the start of the combo');
		}
	});

	i.fire('<w>');
	i.fire('<b>');
});

test('passing a count before a command will execute it with that count', function (t) {
	t.plan(1);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		target: function (count) {
			t.strictEqual(count, 105, 'the mapping was executed with the correct count');
		}
	});

	i.fire('1');
	i.fire('0');
	i.fire('5');
	i.fire('<w>');
});

test('passing a count to a mapping tha does not take one will not execute', function (t) {
	t.plan(0);
	var engine = new MoedCore();
	var i = engine.context.input;

	i.map('<w>', 'normal', 'command', {
		acceptsCount: false,
		target: function () {
			t.fail('execute mapping that does not take a count, should not have');
		}
	});

	i.map('<b>', 'normal', 'command', {
		target: function () {
			t.fail('despite accepting a count, this should not have been executed');
		}
	});

	i.fire('1');
	i.fire('0');
	i.fire('<w>');
	t.end();
});
<|endoftext|>