<commit_before>var cors = require('cors');
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var mongoose = require('mongoose');
var jwt = require('jsonwebtoken');
var fs = require('fs');
var https = require('https');
var expressValidator = require('express-validator');
var session = require('express-session');
var app = express();
var config = require('./config/config');
/**Inicio Express**/
var app = express();
var server = require('http').Server(app);
var secret = config.secret;

var passport = require('passport');
//require('./config/passport')(passport);
var configAuth = require('./config/auth');
var google = require('passport-google-oauth').OAuth2Strategy;
var TwitterStrategy  = require('passport-twitter').Strategy;
app.use(passport.initialize());

var options = {
    key  : fs.readFileSync('server.key'),
    cert : fs.readFileSync('server.crt')
};

/** Express Session **/
app.use(session({
    secret: secret,
    saveUninitialized: true,
    resave: true
}));
/**Set Static Folder**/
app.use(express.static(__dirname + '/public'));
app.set('superSecret', secret);
/** Express Validator **/
app.use(expressValidator({
    errorFormatter: function (param, msg, value) {
        var namespace = param.split('.'), root = namespace.shift(), formParam = root;
        while (namespace.length) {
            formParam += '[' + namespace.shift() + ']';
        }
        return {
            param: formParam,
            msg: msg,
            value: value
        };
    }
}));
/**Middlewares express**/
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
/** developing mode **/
/** use morgan to log requests to the console**/
var morgan = require('morgan');
app.use(morgan('dev'));
/**CORS Filter**/
app.use(cors());
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Access-Token");
    next();
});
app.get('/', function (req, res) {
    res.send('Hello! The API is at http://localhost:' + config.port + '/api');
});
/**------------------------------------------------------------------ **/
/**--------------------IMPORT of Models & Controllers---------------- **/
/**------------------------------------------------------------------ **/
var userMdl = require('./models/userModel');
var userCtrl = require('./controllers/userController');
var dietMdl = require('./models/dietModel')(app, mongoose);
var dietCtrl = require('./controllers/dietController');
var routineMdl = require('./models/routineModel')(app, mongoose);
var routineCtrl = require('./controllers/routineController');
var trainerCtrl = require('./controllers/trainerController');
var chefCtrl = require('./controllers/chefController');
var publicationMdl = require('./models/publicationModel')(app, mongoose);
var publicationCtrl = require('./controllers/publicationController');
var conversationMdl = require('./models/conversationModel')(app, mongoose);
var conversationCtrl = require('./controllers/conversationController');
var contactModel = require('./models/contactModel')(app, mongoose);
var contactCtrl = require('./controllers/contactController');
var adminCtrl = require('./controllers/adminController');
var runMdl = require('./models/runModel')(app, mongoose);
var runCtrl = require('./controllers/runController');

/**------------------------------------------------------------------ **/
/**-----------------------------API routes--------------------------- **/
/**------------------------------------------------------------------ **/
var apiRoutes = express.Router();
/**------------------------------------------------------------------ **/
/**----------------------API routes UNprotected---------------------- **/
/**------------------------------------------------------------------ **/
/**Users**/
apiRoutes.route('/users/register')
    .post(userCtrl.register);
apiRoutes.route('/users/login')
    .post(userCtrl.login);
apiRoutes.route('/logout')
    .post(userCtrl.logout);
/**Chefs**/
apiRoutes.route('/chefs/register')
    .post(chefCtrl.register);
apiRoutes.route('/chefs/login')
    .post(chefCtrl.login);
apiRoutes.route('/chefs')
    .get(chefCtrl.getChefs);
apiRoutes.route('/chefs/:chefid')
    .get(chefCtrl.getChefById);
/**Trainers**/
apiRoutes.route('/trainers/register')
    .post(trainerCtrl.register);
apiRoutes.route('/trainers/login')
    .post(trainerCtrl.login);
apiRoutes.route('/trainers')
    .get(trainerCtrl.getTrainers);
apiRoutes.route('/trainers/:trainerid')
    .get(trainerCtrl.getTrainerById);
apiRoutes.route('/trainers/searchByDiscipline')
    .post(trainerCtrl.searchByDiscipline);
/**Diets**/
apiRoutes.route('/diets')
    .get(dietCtrl.getDiets);
apiRoutes.route('/diets/:dietid')
    .get(dietCtrl.getDietById);
/**Routines**/
apiRoutes.route('/routines')
    .get(routineCtrl.getRoutines);
apiRoutes.route('/routines/:routineid')
    .get(routineCtrl.getRoutineById);
/**Contact**/
apiRoutes.route('/contacts')
    .get(contactCtrl.getContacts)
    .post(contactCtrl.createContact);
apiRoutes.route('/contacts/:contactid')
    .get(contactCtrl.getContactById);

passport.use(new TwitterStrategy({
    consumerKey     : configAuth.twitterAuth.consumerKey,
    consumerSecret  : configAuth.twitterAuth.consumerSecret,
    callbackURL     : configAuth.twitterAuth.callbackURL
}, function(token, refreshToken, profile, done) {

        userMdl.findOne({ 'twitter.id' : profile.id }, function(err, user) {
            // if there is an error, stop everything and return that
            // ie an error connecting to the database
            if (err)
            {
                console.log(err);
                return done(err);
            }

            // if the user is found then log them in
            if (user) {
                var newToken = {
                    token: token,
                    lastLogin: Date()
                };
                user.tokens[0]=newToken;
                // save our user into the database
                user.save(function(err) {
                    if (err)
                        throw err;

                    return done(null, user); // user found, return that user
                });
            } else {
                // if there is no user, create them
                var newUser                 = new userMdl();

                // set all of the user data that we need
                newUser.twitter.id          = profile.id;
                newUser.twitter.token       = token;
                newUser.twitter.username    = profile.username;
                newUser.twitter.displayName = profile.displayName;

                newUser.avatar      = profile._json.profile_image_url;
                newUser.background  = profile._json.profile_background_image_url;
                newUser.name = profile.displayName;
                newUser.role = "user";
                newUser.email = profile.username + "@foodsports.com";
                newUser.tokens=[];
                var newToken = {
                    token: token,
                    lastLogin: Date()
                };
                newUser.tokens.push(newToken);

                // save our user into the database
                newUser.save(function(err) {
                    if (err)
                        throw err;
                    return done(null, newUser);
                });
            }
        });

}));
passport.serializeUser(function(user, done) {
    console.log("serialize");
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    console.log("deserialize");
    userMdl.findById(id, function(err, user) {
        done(err, user);
    });
});
apiRoutes.get('/auth/twitter', passport.authenticate('twitter'));
apiRoutes.get('/auth/twitter/callback', passport.authenticate('twitter',
    {
        failureRedirect : 'http://localhost:8000/#!/login'
    },
    function(req, res, err, user) {
        console.log("res");
        console.log(res);
        //res.redirect('/api/passport');
    })
);

apiRoutes.get('/passport', function(req, res){
    console.log(req);
    res.send(200, "a");
});
/**------------------------------------------------------------------ **/
/**-----------------------API routes Protected----------------------- **/
/**------------------------------------------------------------------ **/
/**Used to check if the Token is valid**/
/**Everything after this is protected route**/
/** start of TOKEN MATCHING **/

apiRoutes.use(function (req, res, next) {
    var token = req.body.token || req.query.token || req.headers['x-access-token'];
    if (token) {
        jwt.verify(token, app.get('superSecret'), function (err, decoded) {
            if (err) {
                return res.json({success: false, message: 'Failed to authenticate token.'});
            } else {
                req.decoded = decoded;
                next();
            }
        });
    } else {
        return res.status(403).send({
            success: false,
            message: 'No token provided.'
        });
    }
});
/** end of TOKEN MATCHING **/

/** ********** **/
/******GLOBAL*****/
/** ********** **/

apiRoutes.route('/search/:searchstring')
    .get(userCtrl.search);

/** ********** **/
/******USERS*****/
/** ********** **/

apiRoutes.route('/users')
    .get(userCtrl.getUsers);
apiRoutes.route('/users/:userid')
    .get(userCtrl.getUserById)
    .put(userCtrl.updateUser)
    .delete(userCtrl.deleteUserById);
apiRoutes.route('/users/upload')
    .post(userCtrl.avatarUpload);
apiRoutes.route('/users/:userid/diets')
    .get(userCtrl.getDietsFromUserId);
apiRoutes.route('/users/:userid/routines')
    .get(userCtrl.getRoutinesFromUserId);
apiRoutes.route('/users/:userid/publications')
    .get(publicationCtrl.getUserPublicationsByUserId);
apiRoutes.route('/users/sendPetitionToTrainer/:trainerid')
    .post(userCtrl.sendPetitionToTrainer);
apiRoutes.route('/notifications')
    .get(userCtrl.getNotifications);
apiRoutes.route('/notificationsNumber')
    .get(userCtrl.getNumberOfNotifications);
apiRoutes.route('/users/:userid/deleteSelectedTokens')
    .post(userCtrl.deleteSelectedTokens);
apiRoutes.route('/users/follow')
    .post(userCtrl.follow);
apiRoutes.route('/users/unfollow')
    .post(userCtrl.unfollow);
apiRoutes.route('/users/:userid/network')
    .get(userCtrl.getUserNetworkById);
apiRoutes.route('/users/:userid/suggestions')
    .get(userCtrl.getUserSuggestionsById);
apiRoutes.route('/users/newMark')
    .post(userCtrl.newMark);
apiRoutes.route('/users/marks/:markid')//no podiem posar directament /users/:marksid, pq llavors pilla com si fos /users/:userid i no té forma de saber que ens referim a una mark
    .delete(userCtrl.deleteUserMark);
apiRoutes.route('/users/marks/:markid/addDayToMark')
    .post(userCtrl.addDayToMark);

/** *********** **/
/*** TRAINERS ****/
/** *********** **/

apiRoutes.route('/trainers/:trainerid')
    .put(trainerCtrl.updateTrainer)
    .delete(trainerCtrl.removeTrainer);
apiRoutes.route('/trainers/acceptClientPetition')
    .post(trainerCtrl.acceptClientPetition);
apiRoutes.route('/trainers/valorate/:trainerid')
    .post(trainerCtrl.valorateTrainer);
apiRoutes.route('/trainers/:trainerid/getNotifications')
    .get(trainerCtrl.getNotifications);
apiRoutes.route('/trainers/searchByName/:trainername')
    .get(trainerCtrl.searchByName);
apiRoutes.route('/trainers/searchByDiscipline/:discipline')
    .get(trainerCtrl.searchByDiscipline);
apiRoutes.route('/trainersSuggestionsByDisciplines')
    .get(trainerCtrl.getTrainersByDisciplinesArray);

/** ********** **/
/******CHEFS*****/
/** ********** **/

apiRoutes.route('/chefs/:chefid')
    .put(chefCtrl.updateChefById)
    .delete(chefCtrl.deleteChefById);

/** ********** **/
/******DIETS*****/
/** ********** **/

apiRoutes.route('/diets')
    .post(dietCtrl.createDiet);
apiRoutes.route('/diets/:dietid/days')
    .post(dietCtrl.addDayToDiet);
apiRoutes.route('/diets/:dietid')
    .delete(dietCtrl.deleteDietById)
    .put(dietCtrl.updateDietById);
apiRoutes.route('/diets/choose/:dietid')
    .post(dietCtrl.chooseDiet)
    .delete(dietCtrl.unchooseDiet);
apiRoutes.route('/diets/completeDay/:dietid')
    .post(dietCtrl.completeDayGamificatedDiet);

/** ********** **/
/****ROUTINES****/
/** ********** **/

apiRoutes.route('/routines/addToClient/:clientid')
    .post(routineCtrl.addRoutineToClient);
apiRoutes.route('/routines/:routineid/days')
    .post(routineCtrl.addDayToRoutine);
apiRoutes.route('/routines/choose')
    .post(routineCtrl.chooseRoutine)
    .delete(routineCtrl.unchooseRoutine);
apiRoutes.route('/routines/:routineid')
    .delete(routineCtrl.deleteRoutineById)
    .put(routineCtrl.updateRoutineById);
apiRoutes.route('/routines/completeDay/:routineid')
    .post(routineCtrl.completeDayGamificatedRoutine);

/** ********** **/
/**PUBLICATIONS**/
/** ********** **/

apiRoutes.route('/publications')
    .get(publicationCtrl.getAllPublications)
    .post(publicationCtrl.postPublication);
apiRoutes.route('/publications/getById/:publicationid')
    .get(publicationCtrl.getPublicationById);
apiRoutes.route('/publications/:publicationid/like')
    .post(publicationCtrl.likePublication);
apiRoutes.route('/publications/:publicationid/dislike')
    .post(publicationCtrl.dislikePublication);
apiRoutes.route('/publications/:publicationid')
    .delete(publicationCtrl.deletePublicationById);
apiRoutes.route('/publications/newsfeed')
    .get(publicationCtrl.getNewsFeed);

/** ********** **/
/**CONVERSATIONS**/
/** ********** **/

apiRoutes.route('/conversations')
    .get(conversationCtrl.getUserConversations)
    .post(conversationCtrl.createConversation);
apiRoutes.route('/conversations/:conversationid')
    .post(conversationCtrl.addMessageToConversation);

/** ********** **/
/**RUNS**/
/** ********** **/

apiRoutes.route('/runs')
    .post(runCtrl.postRun);
apiRoutes.route('/runs/byUserId/:userid')
    .get(runCtrl.getRunsByUserId);
apiRoutes.route('/runs/byRunId/:runid')
    .get(runCtrl.getRunByRunId);

/** ********** **/
/**ADMIN**/
/** ********** **/

apiRoutes.route('/admin/users')
    .get(adminCtrl.getUsers);

apiRoutes.route('/admin/nodesMap/:userid')
    .get(adminCtrl.getUserById);

app.use('/api', apiRoutes);
/**-------------------------------------------------------------**/
/**--------------------END of API routes------------------------**/
/**-------------------------------------------------------------**/

/**Conexión a la base de datos de MongoDB que tenemos en local**/
mongoose.Promise = global.Promise;
require('mongoose-middleware').initialize(mongoose);
mongoose.connect(config.database, function (err) {
    if (err) throw err;
    console.log('Conectado con éxito a la Base de Datos');
});
/** Start server **/
server.listen(config.port, function () {
    console.log("Servidor en http://localhost:" + config.port);
});

https.createServer(options, app).listen(3000, function () {
    console.log('Started!');
});
<commit_msg>ruta byId<commit_after>var cors = require('cors');
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var mongoose = require('mongoose');
var jwt = require('jsonwebtoken');
var fs = require('fs');
var https = require('https');
var expressValidator = require('express-validator');
var session = require('express-session');
var app = express();
var config = require('./config/config');
/**Inicio Express**/
var app = express();
var server = require('http').Server(app);
var secret = config.secret;

var passport = require('passport');
//require('./config/passport')(passport);
var configAuth = require('./config/auth');
var google = require('passport-google-oauth').OAuth2Strategy;
var TwitterStrategy  = require('passport-twitter').Strategy;
app.use(passport.initialize());

var options = {
    key  : fs.readFileSync('server.key'),
    cert : fs.readFileSync('server.crt')
};

/** Express Session **/
app.use(session({
    secret: secret,
    saveUninitialized: true,
    resave: true
}));
/**Set Static Folder**/
app.use(express.static(__dirname + '/public'));
app.set('superSecret', secret);
/** Express Validator **/
app.use(expressValidator({
    errorFormatter: function (param, msg, value) {
        var namespace = param.split('.'), root = namespace.shift(), formParam = root;
        while (namespace.length) {
            formParam += '[' + namespace.shift() + ']';
        }
        return {
            param: formParam,
            msg: msg,
            value: value
        };
    }
}));
/**Middlewares express**/
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
/** developing mode **/
/** use morgan to log requests to the console**/
var morgan = require('morgan');
app.use(morgan('dev'));
/**CORS Filter**/
app.use(cors());
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Access-Token");
    next();
});
app.get('/', function (req, res) {
    res.send('Hello! The API is at http://localhost:' + config.port + '/api');
});
/**------------------------------------------------------------------ **/
/**--------------------IMPORT of Models & Controllers---------------- **/
/**------------------------------------------------------------------ **/
var userMdl = require('./models/userModel');
var userCtrl = require('./controllers/userController');
var dietMdl = require('./models/dietModel')(app, mongoose);
var dietCtrl = require('./controllers/dietController');
var routineMdl = require('./models/routineModel')(app, mongoose);
var routineCtrl = require('./controllers/routineController');
var trainerCtrl = require('./controllers/trainerController');
var chefCtrl = require('./controllers/chefController');
var publicationMdl = require('./models/publicationModel')(app, mongoose);
var publicationCtrl = require('./controllers/publicationController');
var conversationMdl = require('./models/conversationModel')(app, mongoose);
var conversationCtrl = require('./controllers/conversationController');
var contactModel = require('./models/contactModel')(app, mongoose);
var contactCtrl = require('./controllers/contactController');
var adminCtrl = require('./controllers/adminController');
var runMdl = require('./models/runModel')(app, mongoose);
var runCtrl = require('./controllers/runController');

/**------------------------------------------------------------------ **/
/**-----------------------------API routes--------------------------- **/
/**------------------------------------------------------------------ **/
var apiRoutes = express.Router();
/**------------------------------------------------------------------ **/
/**----------------------API routes UNprotected---------------------- **/
/**------------------------------------------------------------------ **/
/**Users**/
apiRoutes.route('/users/register')
    .post(userCtrl.register);
apiRoutes.route('/users/login')
    .post(userCtrl.login);
apiRoutes.route('/logout')
    .post(userCtrl.logout);
/**Chefs**/
apiRoutes.route('/chefs/register')
    .post(chefCtrl.register);
apiRoutes.route('/chefs/login')
    .post(chefCtrl.login);
apiRoutes.route('/chefs')
    .get(chefCtrl.getChefs);
apiRoutes.route('/chefs/:chefid')
    .get(chefCtrl.getChefById);
/**Trainers**/
apiRoutes.route('/trainers/register')
    .post(trainerCtrl.register);
apiRoutes.route('/trainers/login')
    .post(trainerCtrl.login);
apiRoutes.route('/trainers')
    .get(trainerCtrl.getTrainers);
apiRoutes.route('/trainers/:trainerid')
    .get(trainerCtrl.getTrainerById);
apiRoutes.route('/trainers/searchByDiscipline')
    .post(trainerCtrl.searchByDiscipline);
/**Diets**/
apiRoutes.route('/diets')
    .get(dietCtrl.getDiets);
apiRoutes.route('/diets/:dietid')
    .get(dietCtrl.getDietById);
/**Routines**/
apiRoutes.route('/routines')
    .get(routineCtrl.getRoutines);
apiRoutes.route('/routines/:routineid')
    .get(routineCtrl.getRoutineById);
/**Contact**/
apiRoutes.route('/contacts')
    .get(contactCtrl.getContacts)
    .post(contactCtrl.createContact);
apiRoutes.route('/contacts/:contactid')
    .get(contactCtrl.getContactById);

passport.use(new TwitterStrategy({
    consumerKey     : configAuth.twitterAuth.consumerKey,
    consumerSecret  : configAuth.twitterAuth.consumerSecret,
    callbackURL     : configAuth.twitterAuth.callbackURL
}, function(token, refreshToken, profile, done) {

        userMdl.findOne({ 'twitter.id' : profile.id }, function(err, user) {
            // if there is an error, stop everything and return that
            // ie an error connecting to the database
            if (err)
            {
                console.log(err);
                return done(err);
            }

            // if the user is found then log them in
            if (user) {
                var newToken = {
                    token: token,
                    lastLogin: Date()
                };
                user.tokens[0]=newToken;
                // save our user into the database
                user.save(function(err) {
                    if (err)
                        throw err;

                    return done(null, user); // user found, return that user
                });
            } else {
                // if there is no user, create them
                var newUser                 = new userMdl();

                // set all of the user data that we need
                newUser.twitter.id          = profile.id;
                newUser.twitter.token       = token;
                newUser.twitter.username    = profile.username;
                newUser.twitter.displayName = profile.displayName;

                newUser.avatar      = profile._json.profile_image_url;
                newUser.background  = profile._json.profile_background_image_url;
                newUser.name = profile.displayName;
                newUser.role = "user";
                newUser.email = profile.username + "@foodsports.com";
                newUser.tokens=[];
                var newToken = {
                    token: token,
                    lastLogin: Date()
                };
                newUser.tokens.push(newToken);

                // save our user into the database
                newUser.save(function(err) {
                    if (err)
                        throw err;
                    return done(null, newUser);
                });
            }
        });

}));
passport.serializeUser(function(user, done) {
    console.log("serialize");
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    console.log("deserialize");
    userMdl.findById(id, function(err, user) {
        done(err, user);
    });
});
apiRoutes.get('/auth/twitter', passport.authenticate('twitter'));
apiRoutes.get('/auth/twitter/callback', passport.authenticate('twitter',
    {
        failureRedirect : 'http://localhost:8000/#!/login'
    },
    function(req, res, err, user) {
        console.log("res");
        console.log(res);
        //res.redirect('/api/passport');
    })
);

apiRoutes.get('/passport', function(req, res){
    console.log(req);
    res.send(200, "a");
});
/**------------------------------------------------------------------ **/
/**-----------------------API routes Protected----------------------- **/
/**------------------------------------------------------------------ **/
/**Used to check if the Token is valid**/
/**Everything after this is protected route**/
/** start of TOKEN MATCHING **/

apiRoutes.use(function (req, res, next) {
    var token = req.body.token || req.query.token || req.headers['x-access-token'];
    if (token) {
        jwt.verify(token, app.get('superSecret'), function (err, decoded) {
            if (err) {
                return res.json({success: false, message: 'Failed to authenticate token.'});
            } else {
                req.decoded = decoded;
                next();
            }
        });
    } else {
        return res.status(403).send({
            success: false,
            message: 'No token provided.'
        });
    }
});
/** end of TOKEN MATCHING **/

/** ********** **/
/******GLOBAL*****/
/** ********** **/

apiRoutes.route('/search/:searchstring')
    .get(userCtrl.search);

/** ********** **/
/******USERS*****/
/** ********** **/

apiRoutes.route('/users')
    .get(userCtrl.getUsers);
apiRoutes.route('/users/:userid')
    .get(userCtrl.getUserById)
    .put(userCtrl.updateUser)
    .delete(userCtrl.deleteUserById);
apiRoutes.route('/users/upload')
    .post(userCtrl.avatarUpload);
apiRoutes.route('/users/:userid/diets')
    .get(userCtrl.getDietsFromUserId);
apiRoutes.route('/users/:userid/routines')
    .get(userCtrl.getRoutinesFromUserId);
apiRoutes.route('/users/:userid/publications')
    .get(publicationCtrl.getUserPublicationsByUserId);
apiRoutes.route('/users/sendPetitionToTrainer/:trainerid')
    .post(userCtrl.sendPetitionToTrainer);
apiRoutes.route('/notifications')
    .get(userCtrl.getNotifications);
apiRoutes.route('/notificationsNumber')
    .get(userCtrl.getNumberOfNotifications);
apiRoutes.route('/users/:userid/deleteSelectedTokens')
    .post(userCtrl.deleteSelectedTokens);
apiRoutes.route('/users/follow')
    .post(userCtrl.follow);
apiRoutes.route('/users/unfollow')
    .post(userCtrl.unfollow);
apiRoutes.route('/users/:userid/network')
    .get(userCtrl.getUserNetworkById);
apiRoutes.route('/users/:userid/suggestions')
    .get(userCtrl.getUserSuggestionsById);
apiRoutes.route('/users/newMark')
    .post(userCtrl.newMark);
apiRoutes.route('/users/marks/:markid')//no podiem posar directament /users/:marksid, pq llavors pilla com si fos /users/:userid i no té forma de saber que ens referim a una mark
    .delete(userCtrl.deleteUserMark);
apiRoutes.route('/users/marks/:markid/addDayToMark')
    .post(userCtrl.addDayToMark);

/** *********** **/
/*** TRAINERS ****/
/** *********** **/

apiRoutes.route('/trainers/:trainerid')
    .put(trainerCtrl.updateTrainer)
    .delete(trainerCtrl.removeTrainer);
apiRoutes.route('/trainers/acceptClientPetition')
    .post(trainerCtrl.acceptClientPetition);
apiRoutes.route('/trainers/valorate/:trainerid')
    .post(trainerCtrl.valorateTrainer);
apiRoutes.route('/trainers/:trainerid/getNotifications')
    .get(trainerCtrl.getNotifications);
apiRoutes.route('/trainers/searchByName/:trainername')
    .get(trainerCtrl.searchByName);
apiRoutes.route('/trainers/searchByDiscipline/:discipline')
    .get(trainerCtrl.searchByDiscipline);
apiRoutes.route('/trainersSuggestionsByDisciplines')
    .get(trainerCtrl.getTrainersByDisciplinesArray);

/** ********** **/
/******CHEFS*****/
/** ********** **/

apiRoutes.route('/chefs/:chefid')
    .put(chefCtrl.updateChefById)
    .delete(chefCtrl.deleteChefById);

/** ********** **/
/******DIETS*****/
/** ********** **/

apiRoutes.route('/diets')
    .post(dietCtrl.createDiet);
apiRoutes.route('/diets/:dietid/days')
    .post(dietCtrl.addDayToDiet);
apiRoutes.route('/diets/byId/:dietid')
    .delete(dietCtrl.deleteDietById)
    .put(dietCtrl.updateDietById);
apiRoutes.route('/diets/choose/:dietid')
    .post(dietCtrl.chooseDiet)
    .delete(dietCtrl.unchooseDiet);
apiRoutes.route('/diets/completeDay/:dietid')
    .post(dietCtrl.completeDayGamificatedDiet);

/** ********** **/
/****ROUTINES****/
/** ********** **/

apiRoutes.route('/routines/addToClient/:clientid')
    .post(routineCtrl.addRoutineToClient);
apiRoutes.route('/routines/:routineid/days')
    .post(routineCtrl.addDayToRoutine);
apiRoutes.route('/routines/choose')
    .post(routineCtrl.chooseRoutine)
    .delete(routineCtrl.unchooseRoutine);
apiRoutes.route('/routines/:routineid')
    .delete(routineCtrl.deleteRoutineById)
    .put(routineCtrl.updateRoutineById);
apiRoutes.route('/routines/completeDay/:routineid')
    .post(routineCtrl.completeDayGamificatedRoutine);

/** ********** **/
/**PUBLICATIONS**/
/** ********** **/

apiRoutes.route('/publications')
    .get(publicationCtrl.getAllPublications)
    .post(publicationCtrl.postPublication);
apiRoutes.route('/publications/getById/:publicationid')
    .get(publicationCtrl.getPublicationById);
apiRoutes.route('/publications/:publicationid/like')
    .post(publicationCtrl.likePublication);
apiRoutes.route('/publications/:publicationid/dislike')
    .post(publicationCtrl.dislikePublication);
apiRoutes.route('/publications/:publicationid')
    .delete(publicationCtrl.deletePublicationById);
apiRoutes.route('/publications/newsfeed')
    .get(publicationCtrl.getNewsFeed);

/** ********** **/
/**CONVERSATIONS**/
/** ********** **/

apiRoutes.route('/conversations')
    .get(conversationCtrl.getUserConversations)
    .post(conversationCtrl.createConversation);
apiRoutes.route('/conversations/:conversationid')
    .post(conversationCtrl.addMessageToConversation);

/** ********** **/
/**RUNS**/
/** ********** **/

apiRoutes.route('/runs')
    .post(runCtrl.postRun);
apiRoutes.route('/runs/byUserId/:userid')
    .get(runCtrl.getRunsByUserId);
apiRoutes.route('/runs/byRunId/:runid')
    .get(runCtrl.getRunByRunId);

/** ********** **/
/**ADMIN**/
/** ********** **/

apiRoutes.route('/admin/users')
    .get(adminCtrl.getUsers);

apiRoutes.route('/admin/nodesMap/:userid')
    .get(adminCtrl.getUserById);

app.use('/api', apiRoutes);
/**-------------------------------------------------------------**/
/**--------------------END of API routes------------------------**/
/**-------------------------------------------------------------**/

/**Conexión a la base de datos de MongoDB que tenemos en local**/
mongoose.Promise = global.Promise;
require('mongoose-middleware').initialize(mongoose);
mongoose.connect(config.database, function (err) {
    if (err) throw err;
    console.log('Conectado con éxito a la Base de Datos');
});
/** Start server **/
server.listen(config.port, function () {
    console.log("Servidor en http://localhost:" + config.port);
});

https.createServer(options, app).listen(3000, function () {
    console.log('Started!');
});
<|endoftext|>


<commit_before>// Based on https://github.com/fbsamples/messenger-platform-samples/tree/master/node
const crypto = require('crypto');
const EventEmitter = require('events');

const bodyParser = require('body-parser');
const Cacheman = require('cacheman');
const dashbot = require('dashbot');
const debug = require('debug')('lenses:messenger');
const express = require('express');
const exphbs = require('express-handlebars');
const logError = require('debug')('lenses:messenger:error');
const reqPromise = require('request-promise');
const urlJoin = require('url-join');
const conversationLogger = require('./conversationLogger');

const cache = new Cacheman('sessions');

const SESSION_TIMEOUT_MS = 3600 * 1000;  // 1 hour

const internals = {};

class Messenger extends EventEmitter {
  constructor(config, {hookPath = '/webhook', linkPath = '/link'} = {}) {
    super();

    this.config = config;

    this.options = {
      hookPath,
      linkPath
    };

    this.app = express();
    this.app.engine('handlebars', exphbs({defaultLayout: 'main'}));
    this.app.set('view engine', 'handlebars');

    this.app.use(bodyParser.json({ verify: this.verifyRequestSignature.bind(this) }));
    this.app.use(bodyParser.urlencoded({ extended: true }));
    this.app.use(express.static('public'));

    if (this.config.has('dashbotKey')) {
      this.dashbotClient = dashbot(this.config.get('dashbotKey')).facebook;
    } else {
      debug('No DASHBOT_KEY specified; no data will be sent to DashBot.');
    }

    // Facebook Messenger verification
    this.app.get(hookPath, (req, res) => {
      if (req.query['hub.mode'] === 'subscribe' &&
      req.query['hub.verify_token'] === this.config.get('messenger.validationToken')) {
        debug('Validating webhook');
        res.status(200).send(req.query['hub.challenge']);
      } else {
        debug('Failed validation. Make sure the validation tokens match.');
        res.sendStatus(403);
      }
    });

    this.app.post(hookPath, (req, res) => {
      const data = req.body;
      if (this.dashbotClient) {
        this.dashbotClient.logIncoming(data);
      }
      conversationLogger.logIncoming(data);
      // `data` reference:
      // https://developers.facebook.com/docs/messenger-platform/webhook-reference#format
      if (data.object === 'page') {
        data.entry.forEach((pageEntry) => {
          pageEntry.messaging.forEach(this.routeEachMessage.bind(this));
        });
        res.sendStatus(200);
      }
    });

    this.app.post(linkPath, (req, res) => {
      this.onLink(req.body);
      res.sendStatus(200);
    });

    // App routes
    this.app.get('/login', (req, res) => res.render('login', {
      appId: this.config.get('facebook.appId'),
      serverUrl: this.config.get('serverUrl')
    }));
    this.app.get('/send-to-messenger', (req, res) => res.render('send-to-messenger', {
      appId: this.config.get('facebook.appId'),
      pageId: this.config.get('facebook.pageId')
    }));

    this.app.get('/', (req, res) => {
      res.send('👍');
    });

    this.app.get('/ping', (req, res) => {
      res.send('Departures healthcheck OK');
    });
  }

  start() {
    const port = this.config.get('port');
    this.app.listen(port, (err) => {
      if (err) throw err;
      debug('Server running on port %s', port);
      // TODO console.log(`Set your webhook to: `)
    });
  }

  routeEachMessage(messagingEvent) {
    const cacheKey = messagingEvent.sender.id;
    return cache.get(cacheKey)
      .then((session = {_key: cacheKey, count: 0}) => {
        session.count++;
        if (session.source !== 'return' &&
            session.lastSeen &&
            // have to use `internals` here for testability
            new Date().getTime() - session.lastSeen > internals.SESSION_TIMEOUT_MS) {
          session.source = 'return';
        }
        session.lastSeen = new Date().getTime();
        if (messagingEvent.optin) {
          debug('incoming authentication event');
          session.source = 'web';
          this.onAuth(messagingEvent, session);
        } else if (messagingEvent.message) {
          debug('incoming message');
          this.onMessage(messagingEvent, session);
        } else if (messagingEvent.delivery) {
          debug('incoming delivery event');
        } else if (messagingEvent.postback) {
          debug('incoming postback');
          this.onPostback(messagingEvent, session);
        } else if (messagingEvent.read) {
          debug('incoming read event');
        } else {
          debug('incoming unknown messagingEvent: %o', messagingEvent);
        }
        return session;
      })
      .then((session) => this.saveSession(session));
  }

  doLogin(senderId) {
    // Open question: is building the event object worth it for the 'emit'?
    const event = {
      sender: {id: senderId},
      recipient: {id: this.config.get('facebook.pageId')},
      timestamp: new Date().getTime()
    };
    this.emit('login', {event, senderId});
    debug('Received login request for user %d', senderId);

    const messageData = {
      attachment: {
        type: 'template',
        payload: {
          template_type: 'generic',
          elements: [{
            title: 'Login With Facebook',
            subtitle: '',
            buttons: [{
              type: 'web_url',
              url: urlJoin(this.config.get('serverUrl'), `login?userId=${senderId}`),
              title: 'Login With Facebook'
            }]
          }]
        }
      }
    };
    this.send(senderId, messageData);
  }

  getPublicProfile(senderId) {
    const options = {
      json: true,
      qs: {
        access_token: this.config.get('messenger.pageAccessToken'),
        fields: 'first_name,last_name,profile_pic,locale,timezone,gender'
      },
      url: `https://graph.facebook.com/v2.6/${senderId}`
    };
    return reqPromise(options)
      .then((jsonObj) => {
        return jsonObj;
      })
      .catch((err) => {
        logError('Failed calling Graph API', err.message);
        return {};
      });
  }

  // EVENTS
  /////////

  onAuth(event, session) {
    const senderId = event.sender.id;
    // The 'ref' is the data passed through the 'Send to Messenger' call
    const optinRef = event.optin.ref;
    this.emit('auth', {event, senderId, session, optinRef});
    debug('Received auth for user %d with param: %o', senderId, optinRef);
  }

  /*
    This is not an event triggered by Messenger, it is the post-back from the
    static Facebook login page that is made to look similar to an 'event'
  */
  onLink(event) {
    const senderId = event.sender.id;
    const recipientId = event.recipient.id;
    const timeOfLink = event.timestamp;

    const fbData = event.facebook;
    debug('Received link for user %d and page %d at %d with data:\n%o',
      senderId, recipientId, timeOfLink, fbData);
    return this.emit('link', {event, senderId, fbData});
  }

  onMessage(event, session) {
    const senderId = event.sender.id;
    const {message} = event;

    this.emit('message', {event, senderId, session, message});
    debug('Received message from user %d with message: %j', senderId, message);

    const {
      mid: messageId,
      app_id: appId,
      metadata,
      quick_reply: quickReply,
      // You may get a text or attachment but not both
      text,
      attachments
    } = message;

    if (message.is_echo) {
      debug('Received echo for message %s and app %d with metadata %s', messageId, appId, metadata);
      return;
    }

    if (quickReply) {
      debug('Quick reply for message %s with payload %s', messageId, quickReply.payload);
      this.emit('message.quickReply', {event, senderId, session, payload: quickReply.payload});
      return;
    }

    if (text) {
      debug(text);
      this.emit('message.text', {event, senderId, session, text});
      return;
    }

    if (attachments) {
      // Currently, we can assume there is only one attachment in a message
      const attachment = attachments[0];
      let type = attachment.type;

      if (message.sticker_id) {
        // There's a special thumbsup button in the interface that comes in like a sticker
        // This magic number is intentional.
        type = (message.sticker_id === 369239263222822) ? 'thumbsup' : 'sticker';
      }

      this.emit(`message.${type}`, {event, senderId, session, attachment, url: attachment.payload.url});
      return;
    }
  }

  onPostback(event, session) {
    const senderId = event.sender.id;
    const recipientId = event.recipient.id;
    const timeOfPostback = event.timestamp;

    // The 'payload' param is a developer-defined field which is set in a postback
    // button for Structured Messages.
    const payload = event.postback.payload;

    debug("Received postback for user %d and page %d with payload '%s' at %d",
      senderId, recipientId, payload, timeOfPostback);

    this.emit('postback', {event, senderId, session, payload});
  }

  // HELPERS
  //////////

  saveSession(session) {
    return cache.set(session._key, session);
  }

  send(recipientId, messageData) {
    const options = {
      uri: 'https://graph.facebook.com/v2.8/me/messages',
      qs: { access_token: this.config.get('messenger.pageAccessToken') },
      method: 'POST',
      json: {
        dashbotTemplateId: 'right',
        recipient: {
          id: recipientId
        },
        message: messageData
      }
    };
    debug('Sending message: %j', options);

    return reqPromise(options)
      .then((jsonObj) => {
        if (this.dashbotClient) {
          // TODO should we strip pageAccessToken before giving it to dashbotClient?
          this.dashbotClient.logOutgoing(options, jsonObj);
        }
        conversationLogger.logOutgoing(options, jsonObj);
        const {recipient_id: recipientId, message_id: messageId} = jsonObj;
        debug('Successfully sent message with id %s to recipient %s', messageId, recipientId);
      })
      .catch((err) => {
        logError('Failed calling Send API', err);
      });
  }

  verifyRequestSignature(req, res, buf) {
    const signature = req.headers['x-hub-signature'];

    if (!signature) {
      throw new Error(`Couldn't validate the signature with app secret: ${this.config.get('messenger.appSecret')}`);
    }

    const [method, signatureHash] = signature.split('=');
    // TODO assert method === 'sha1'
    const expectedHash = crypto.createHmac(method, this.config.get('messenger.appSecret')).update(buf).digest('hex');

    if (signatureHash !== expectedHash) {
      throw new Error(`Couldn't validate the request signature: ${this.config.get('messenger.appSecret')}`);
    }
  }
}

internals.cache = cache;
internals.SESSION_TIMEOUT_MS = SESSION_TIMEOUT_MS;
exports.__internals__ = internals;
exports.Messenger = Messenger;
<commit_msg>Refactor: cleanup while browsing through the codebase (#190)<commit_after>const bodyParser = require('body-parser');
const Cacheman = require('cacheman');
const crypto = require('crypto');
const dashbot = require('dashbot');
const debug = require('debug')('lenses:messenger');
const logError = require('debug')('lenses:messenger:error');
const EventEmitter = require('events');
const express = require('express');
const exphbs = require('express-handlebars');
const reqPromise = require('request-promise');
const urlJoin = require('url-join');
const conversationLogger = require('./conversationLogger');

const cache = new Cacheman('sessions');

const SESSION_TIMEOUT_MS = 3600 * 1000;  // 1 hour

const internals = {};

class Messenger extends EventEmitter {
  constructor(config, {hookPath = '/webhook', linkPath = '/link'} = {}) {
    super();

    this.config = config;

    this.options = {
      hookPath,
      linkPath
    };

    this.app = express();
    this.app.engine('handlebars', exphbs({defaultLayout: 'main'}));
    this.app.set('view engine', 'handlebars');

    this.app.use(bodyParser.json({ verify: this.verifyRequestSignature.bind(this) }));
    this.app.use(bodyParser.urlencoded({ extended: true }));
    this.app.use(express.static('public'));

    if (this.config.has('dashbotKey')) {
      this.dashbotClient = dashbot(this.config.get('dashbotKey')).facebook;
    } else {
      debug('No DASHBOT_KEY specified; no data will be sent to DashBot.');
    }

    // Facebook Messenger verification
    this.app.get(hookPath, (req, res) => {
      if (req.query['hub.mode'] === 'subscribe' &&
      req.query['hub.verify_token'] === this.config.get('messenger.validationToken')) {
        debug('Validating webhook');
        res.status(200).send(req.query['hub.challenge']);
      } else {
        debug('Failed validation. Make sure the validation tokens match.');
        res.sendStatus(403);
      }
    });

    this.app.post(hookPath, (req, res) => {
      const data = req.body;
      if (this.dashbotClient) {
        this.dashbotClient.logIncoming(data);
      }
      conversationLogger.logIncoming(data);
      // `data` reference:
      // https://developers.facebook.com/docs/messenger-platform/webhook-reference#format
      if (data.object === 'page') {
        data.entry.forEach((pageEntry) => {
          pageEntry.messaging.forEach(this.routeEachMessage.bind(this));
        });
        res.sendStatus(200);
      }
    });

    this.app.post(linkPath, (req, res) => {
      this.onLink(req.body);
      res.sendStatus(200);
    });

    // App routes
    this.app.get('/login', (req, res) => res.render('login', {
      appId: this.config.get('facebook.appId'),
      serverUrl: this.config.get('serverUrl')
    }));
    this.app.get('/send-to-messenger', (req, res) => res.render('send-to-messenger', {
      appId: this.config.get('facebook.appId'),
      pageId: this.config.get('facebook.pageId')
    }));

    this.app.get('/', (req, res) => {
      res.send('👍');
    });

    this.app.get('/ping', (req, res) => {
      res.send('Departures healthcheck OK');
    });
  }

  start() {
    const port = this.config.get('port');
    this.app.listen(port, (err) => {
      if (err) throw err;
      debug('Server running on port %s', port);
      // TODO console.log(`Set your webhook to: `)
    });
  }

  routeEachMessage(messagingEvent) {
    const cacheKey = messagingEvent.sender.id;
    return cache.get(cacheKey)
      .then((session = {_key: cacheKey, count: 0}) => {
        session.count++;
        if (session.source !== 'return' &&
            session.lastSeen &&
            // have to use `internals` here for testability
            new Date().getTime() - session.lastSeen > internals.SESSION_TIMEOUT_MS) {
          session.source = 'return';
        }
        session.lastSeen = new Date().getTime();
        if (messagingEvent.optin) {
          session.source = 'web';
          this.onAuth(messagingEvent, session);
        } else if (messagingEvent.message) {
          this.onMessage(messagingEvent, session);
        } else if (messagingEvent.delivery) {
          debug('incoming delivery event');
        } else if (messagingEvent.postback) {
          this.onPostback(messagingEvent, session);
        } else if (messagingEvent.read) {
          debug('incoming read event');
        } else {
          debug('incoming unknown messagingEvent: %o', messagingEvent);
        }
        return session;
      })
      .then((session) => this.saveSession(session));
  }

  doLogin(senderId) {
    // Open question: is building the event object worth it for the 'emit'?
    const event = {
      sender: {id: senderId},
      recipient: {id: this.config.get('facebook.pageId')},
      timestamp: new Date().getTime()
    };
    this.emit('login', {event, senderId});
    debug('doLogin request for user %d', senderId);

    const messageData = {
      attachment: {
        type: 'template',
        payload: {
          template_type: 'generic',
          elements: [{
            title: 'Login With Facebook',
            subtitle: '',
            buttons: [{
              type: 'web_url',
              url: urlJoin(this.config.get('serverUrl'), `login?userId=${senderId}`),
              title: 'Login With Facebook'
            }]
          }]
        }
      }
    };
    this.send(senderId, messageData);
  }

  getPublicProfile(senderId) {
    const options = {
      json: true,
      qs: {
        access_token: this.config.get('messenger.pageAccessToken'),
        fields: 'first_name,last_name,profile_pic,locale,timezone,gender'
      },
      url: `https://graph.facebook.com/v2.6/${senderId}`
    };
    return reqPromise(options)
      .catch((err) => {
        logError('Failed calling Graph API', err.message);
        return {};
      });
  }

  // EVENTS
  /////////

  onAuth(event, session) {
    const senderId = event.sender.id;
    // The 'ref' is the data passed through the 'Send to Messenger' call
    const optinRef = event.optin.ref;
    this.emit('auth', {event, senderId, session, optinRef});
    debug('onAuth for user %d with param: %j', senderId, optinRef);
  }

  /*
    This is not an event triggered by Messenger, it is the post-back from the
    static Facebook login page that is made to look similar to an 'event'
  */
  onLink(event) {
    const senderId = event.sender.id;
    const fbData = event.facebook;
    debug('Received link for user %d with data: %o', senderId, fbData);
    this.emit('link', {event, senderId, fbData});
    return;
  }

  onMessage(event, session) {
    const senderId = event.sender.id;
    const {message} = event;

    this.emit('message', {event, senderId, session, message});
    debug('onMessage from user %d with message: %j', senderId, message);

    const {
      mid: messageId,
      app_id: appId,
      metadata,
      quick_reply: quickReply,
      // You may get a text or attachment but not both
      text,
      attachments
    } = message;

    if (message.is_echo) {
      debug('Received echo for message %s and app %d with metadata %s', messageId, appId, metadata);
      return;
    }

    if (quickReply) {
      debug('Quick reply for message %s with payload %s', messageId, quickReply.payload);
      this.emit('message.quickReply', {event, senderId, session, payload: quickReply.payload});
      return;
    }

    if (text) {
      debug(text);
      this.emit('message.text', {event, senderId, session, text});
      return;
    }

    if (attachments) {
      // Currently, we can assume there is only one attachment in a message
      const attachment = attachments[0];
      let type = attachment.type;

      if (message.sticker_id) {
        // There's a special thumbsup button in the interface that comes in like a sticker
        // This magic number is intentional.
        type = (message.sticker_id === 369239263222822) ? 'thumbsup' : 'sticker';
      }

      this.emit(`message.${type}`, {event, senderId, session, attachment, url: attachment.payload.url});
      return;
    }
  }

  onPostback(event, session) {
    const senderId = event.sender.id;

    // The 'payload' param is a developer-defined field which is set in a postback
    // button for Structured Messages.
    const payload = event.postback.payload;

    debug("onPostback for user %d with payload '%s'", senderId, payload);

    this.emit('postback', {event, senderId, session, payload});
  }

  // HELPERS
  //////////

  saveSession(session) {
    return cache.set(session._key, session);
  }

  send(recipientId, messageData) {
    const options = {
      uri: 'https://graph.facebook.com/v2.8/me/messages',
      qs: { access_token: this.config.get('messenger.pageAccessToken') },
      method: 'POST',
      json: {
        dashbotTemplateId: 'right',
        recipient: {
          id: recipientId
        },
        message: messageData
      }
    };
    debug('Sending message: %j', options);

    return reqPromise(options)
      .then((jsonObj) => {
        if (this.dashbotClient) {
          // TODO should we strip pageAccessToken before giving it to dashbotClient?
          this.dashbotClient.logOutgoing(options, jsonObj);
        }
        conversationLogger.logOutgoing(options, jsonObj);
        const {recipient_id: recipientId, message_id: messageId} = jsonObj;
        debug('Successfully sent message: %s to recipient: %s', messageId, recipientId);
      })
      .catch((err) => {
        logError('Failed calling Send API', err);
      });
  }

  verifyRequestSignature(req, res, buf) {
    const signature = req.headers['x-hub-signature'];

    if (!signature) {
      throw new Error(`Couldn't validate the signature with app secret: ${this.config.get('messenger.appSecret')}`);
    }

    const [method, signatureHash] = signature.split('=');
    // TODO assert method === 'sha1'
    const expectedHash = crypto.createHmac(method, this.config.get('messenger.appSecret')).update(buf).digest('hex');

    if (signatureHash !== expectedHash) {
      throw new Error(`Couldn't validate the request signature: ${this.config.get('messenger.appSecret')}`);
    }
  }
}

internals.cache = cache;
internals.SESSION_TIMEOUT_MS = SESSION_TIMEOUT_MS;
exports.__internals__ = internals;
exports.Messenger = Messenger;
<|endoftext|>


<commit_before>console.log('starting the app');
var Hapi = require('hapi');
var Firebase = require('firebase');
var ref = new Firebase('https://debt.firebaseIO.com/');
var request = require('request')

console.log('loading an environment');
var habitat = require('habitat');
habitat.load('.env');

var env = new habitat('firebase');
var firebase_secret = env.get('secret');

var github = new habitat('github');
var token = github.get('token');

console.log("about to auth with firebase");
ref.authWithCustomToken(firebase_secret, function(error, authData) {
  if (error) {
    console.log("Login Failed!", error);
  } else {
    console.log("Authenticated successfully with firebase.");
    // console.log("Authenticated successfully with payload:", authData);
  }
});

var issues = ref.child('issues');
var asks = ref.child('asks');
asks.once('value', function(snapshot) {
  if (snapshot.val() == null) {
    asks.set({});
  }
});
// Create a server with a host and port
var server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: 8000
});

// Add the route
server.route({
    method: 'GET',
    path:'/hello',
    handler: function (request, reply) {
       reply('hello world');
    }
});

var parseComment = function(repository, issue, comment, patchComment) {
  var fromwhom = comment.user.login;
  console.log("Comment on issue: ", repository.name+'/'+String(issue.number) + ' by ' + fromwhom);
  // We'll clear any of the mentions of the author referring to this issue
  var asks_ref = ref.child('asks').child(fromwhom)
  asks_ref.on('value', function(snapshot) {
    var asks_of_author = snapshot.val();
    for (var key in asks_of_author) {
      var ask = asks_of_author[key];
      console.log(ask, ask.issue_id, issue.id)
      if (ask.issue_id == issue.id) {
        // removing an ask
        asks_ref.child(key).remove();
      }
    }
  })
  // For a comment, extract if there are any requests embedded, note who's asking, and add them to a per-askee queue
  var body = comment.body;
  var lines = body.split('\n');
  var newlines = [];
  // console.log(body);

  // We'll add mentions for each of the people mentioned in a comment
  lines.forEach(function (line) {
    // look for things of the syntax <something>? @alias
    // turn " ui-review? @bar;" into [ "", "ui-review", "?", "bar", ";" ]
    re = /\s*([-\w]*)([+-\?])[\s]?=*@(\w*)/i;
    var parts = line.split(re)
    if (parts.length > 1) {
      var question = parts[1];
      var flag = parts[2];
      var towhom = parts[3];
      asks.child(towhom).push({'question':question,
        'flag': flag,
        'issue_id': issue.id,
        'issue': repository.name + '/' + String(issue.number),
        'fromwhom':fromwhom,
        'ref_html_url': comment.html_url,
        'ref_url': comment.url})
      line = line + " `[this was magically recorded as a request]`:wave:";
      newlines.push(line);
    }
  });
  // just check for mentions, regardless of syntax:
  matches = body.match(/(@(\w+))/gi);

  if (matches) {
    matches.forEach(function (match) {
      towhom = match.slice(1,match.length),  // get rid of @;
      asks.child(towhom).push({
        'question': 'mention',
        'issue_id': issue.id,
        'issue': repository.name + '/' + String(issue.number),
        'fromwhom': fromwhom,
        'ref_html_url': comment.html_url,
        'ref_url': comment.url
      })
    })
  }
    // if (parts.length > 1) {
    //   console.log(parts);
      // var question = parts[1];
      // var flag = parts[2];
      // var towhom = parts[3];
      // console.log(question, flag, towhom);
      // asks.child(towhom).push({'question':question,
      //   'flag': flag,
      //   'issue_id': issue.id,
      //   'issue': repository.name + '/' + String(issue.number),
      //   'fromwhom':fromwhom,
      //   'ref_html_url': comment.html_url,
      //   'ref_url': comment.url})
      // line = line + " `[this was magically recorded as a request]`:wave:";
      // newlines.push(line);
  if (patchComment) {
    // update the comment to comment to indicate it's been processed
    var newbody = newlines.join('\n');
    var owner = repository.owner.login;
    var repo = repository.name;
    var url = "https://api.github.com/repos/" + owner + '/' + repo + '/issues/comments/' + comment.id;
    url += "?access_token="+encodeURIComponent(token);
    var options = {
      url: url,
      json: true,
      body: {body: newbody},
      headers: {
          'User-Agent': 'NodeJS HTTP Client'
      }
    };
    request.patch(options, function(err, ret) {
      if (err) {
        console.log(err);
      } else {
        console.log('patched comment!')
      }
    });
  }
}

server.route({
    method: 'POST',
    path:'/postreceive',
    handler: function (request, reply) {
      var eventType = request.headers['x-github-event'];
      if (eventType == 'issues') {
        var issue = issues.child(request.payload.issue.id)
        issue.set(request.payload.issue);
      } else if (eventType == 'issue_comment') {
        var issue = issues.child(request.payload.issue.id);
        issue.transaction(function(currentIssue) {
          if (currentIssue == null) {
            issue.set(request.payload.issue);
          }
          issue.child('comments').child(request.payload.comment.id).set(request.payload.comment);
          parseComment(request.payload.repository, request.payload.issue, request.payload.comment, true);
        })
      }
      reply('OK');
    }
});

server.route({
    method: 'GET',
    path: '/{param*}',
    handler: {
        directory: {
            path: 'public'
        }
    }
});

server.route({
    method: 'POST',
    path:'/add_repo',
    handler: function (req, reply) {
      var org = req.payload.org;
      var repo = req.payload.repo;
      // first get repo info
      var url = "https://api.github.com/repos/" + org + '/' + repo;
      url += "?access_token="+encodeURIComponent(token);
      var options = {
        url: url,
        json: true,
        headers: {
            'User-Agent': 'NodeJS HTTP Client'
        }
      };
      request.get(options, function(err, ret) {
        // now, get the issues
        var repository = ret.body;
        url = repository.url + '/issues';
        url += "?access_token="+encodeURIComponent(token);
        var options = {
          url: url,
          json: true,
          headers: {
              'User-Agent': 'NodeJS HTTP Client'
          }
        };
        request.get(options, function(err, ret) {
          if (err) {
            console.log(err);
          } else {
            // we have the issues
            for (var i=0; i<ret.body.length; i++) {
              var issue = ret.body[i];
              parseComment(repository, issue, issue, false);
              // then get the comments
              url = issue.url + "/comments?access_token="+encodeURIComponent(token);
              var options = {
                url: url,
                json: true,
                headers: {
                    'User-Agent': 'NodeJS HTTP Client'
                }
              };
              (function(issue) {
                request.get(options, function(err, ret) {
                  if (err) {
                    console.log(err);
                  } else {
                    // we have the comments
                    for (var i=0; i<ret.body.length; i++) {
                      var comment = ret.body[i];
                      parseComment(repository, issue, comment, false);
                    }
                  }
                });
              })(issue);
            }
          }
        });
      });
      reply('OK');
    }});

server.route({
    method: 'GET',
    path:'/add_repo',
    handler: function (request, reply) {
      // serve form that suggests we add repos
      reply.file('add_repo.html');
    }
});

// Start the server
server.start();

<commit_msg>duh, forgot to herokufy the server<commit_after>console.log('starting the app');
var Hapi = require('hapi');
var Firebase = require('firebase');
var ref = new Firebase('https://debt.firebaseIO.com/');
var request = require('request')

console.log('loading an environment');
var habitat = require('habitat');
habitat.load('.env');

var env = new habitat('firebase');
var firebase_secret = env.get('secret');

var github = new habitat('github');
var token = github.get('token');

console.log("about to auth with firebase");
ref.authWithCustomToken(firebase_secret, function(error, authData) {
  if (error) {
    console.log("Login Failed!", error);
  } else {
    console.log("Authenticated successfully with firebase.");
    // console.log("Authenticated successfully with payload:", authData);
  }
});

var issues = ref.child('issues');
var asks = ref.child('asks');
asks.once('value', function(snapshot) {
  if (snapshot.val() == null) {
    asks.set({});
  }
});
// Create a server with a host and port
var server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: process.env.PORT || 8000
});

// Add the route
server.route({
    method: 'GET',
    path:'/hello',
    handler: function (request, reply) {
       reply('hello world');
    }
});

var parseComment = function(repository, issue, comment, patchComment) {
  var fromwhom = comment.user.login;
  console.log("Comment on issue: ", repository.name+'/'+String(issue.number) + ' by ' + fromwhom);
  // We'll clear any of the mentions of the author referring to this issue
  var asks_ref = ref.child('asks').child(fromwhom)
  asks_ref.on('value', function(snapshot) {
    var asks_of_author = snapshot.val();
    for (var key in asks_of_author) {
      var ask = asks_of_author[key];
      console.log(ask, ask.issue_id, issue.id)
      if (ask.issue_id == issue.id) {
        // removing an ask
        asks_ref.child(key).remove();
      }
    }
  })
  // For a comment, extract if there are any requests embedded, note who's asking, and add them to a per-askee queue
  var body = comment.body;
  var lines = body.split('\n');
  var newlines = [];
  // console.log(body);

  // We'll add mentions for each of the people mentioned in a comment
  lines.forEach(function (line) {
    // look for things of the syntax <something>? @alias
    // turn " ui-review? @bar;" into [ "", "ui-review", "?", "bar", ";" ]
    re = /\s*([-\w]*)([+-\?])[\s]?=*@(\w*)/i;
    var parts = line.split(re)
    if (parts.length > 1) {
      var question = parts[1];
      var flag = parts[2];
      var towhom = parts[3];
      asks.child(towhom).push({'question':question,
        'flag': flag,
        'issue_id': issue.id,
        'issue': repository.name + '/' + String(issue.number),
        'fromwhom':fromwhom,
        'ref_html_url': comment.html_url,
        'ref_url': comment.url})
      line = line + " `[this was magically recorded as a request]`:wave:";
      newlines.push(line);
    }
  });
  // just check for mentions, regardless of syntax:
  matches = body.match(/(@(\w+))/gi);

  if (matches) {
    matches.forEach(function (match) {
      towhom = match.slice(1,match.length),  // get rid of @;
      asks.child(towhom).push({
        'question': 'mention',
        'issue_id': issue.id,
        'issue': repository.name + '/' + String(issue.number),
        'fromwhom': fromwhom,
        'ref_html_url': comment.html_url,
        'ref_url': comment.url
      })
    })
  }
    // if (parts.length > 1) {
    //   console.log(parts);
      // var question = parts[1];
      // var flag = parts[2];
      // var towhom = parts[3];
      // console.log(question, flag, towhom);
      // asks.child(towhom).push({'question':question,
      //   'flag': flag,
      //   'issue_id': issue.id,
      //   'issue': repository.name + '/' + String(issue.number),
      //   'fromwhom':fromwhom,
      //   'ref_html_url': comment.html_url,
      //   'ref_url': comment.url})
      // line = line + " `[this was magically recorded as a request]`:wave:";
      // newlines.push(line);
  if (patchComment) {
    // update the comment to comment to indicate it's been processed
    var newbody = newlines.join('\n');
    var owner = repository.owner.login;
    var repo = repository.name;
    var url = "https://api.github.com/repos/" + owner + '/' + repo + '/issues/comments/' + comment.id;
    url += "?access_token="+encodeURIComponent(token);
    var options = {
      url: url,
      json: true,
      body: {body: newbody},
      headers: {
          'User-Agent': 'NodeJS HTTP Client'
      }
    };
    request.patch(options, function(err, ret) {
      if (err) {
        console.log(err);
      } else {
        console.log('patched comment!')
      }
    });
  }
}

server.route({
    method: 'POST',
    path:'/postreceive',
    handler: function (request, reply) {
      var eventType = request.headers['x-github-event'];
      if (eventType == 'issues') {
        var issue = issues.child(request.payload.issue.id)
        issue.set(request.payload.issue);
      } else if (eventType == 'issue_comment') {
        var issue = issues.child(request.payload.issue.id);
        issue.transaction(function(currentIssue) {
          if (currentIssue == null) {
            issue.set(request.payload.issue);
          }
          issue.child('comments').child(request.payload.comment.id).set(request.payload.comment);
          parseComment(request.payload.repository, request.payload.issue, request.payload.comment, true);
        })
      }
      reply('OK');
    }
});

server.route({
    method: 'GET',
    path: '/{param*}',
    handler: {
        directory: {
            path: 'public'
        }
    }
});

server.route({
    method: 'POST',
    path:'/add_repo',
    handler: function (req, reply) {
      var org = req.payload.org;
      var repo = req.payload.repo;
      // first get repo info
      var url = "https://api.github.com/repos/" + org + '/' + repo;
      url += "?access_token="+encodeURIComponent(token);
      var options = {
        url: url,
        json: true,
        headers: {
            'User-Agent': 'NodeJS HTTP Client'
        }
      };
      request.get(options, function(err, ret) {
        // now, get the issues
        var repository = ret.body;
        url = repository.url + '/issues';
        url += "?access_token="+encodeURIComponent(token);
        var options = {
          url: url,
          json: true,
          headers: {
              'User-Agent': 'NodeJS HTTP Client'
          }
        };
        request.get(options, function(err, ret) {
          if (err) {
            console.log(err);
          } else {
            // we have the issues
            for (var i=0; i<ret.body.length; i++) {
              var issue = ret.body[i];
              parseComment(repository, issue, issue, false);
              // then get the comments
              url = issue.url + "/comments?access_token="+encodeURIComponent(token);
              var options = {
                url: url,
                json: true,
                headers: {
                    'User-Agent': 'NodeJS HTTP Client'
                }
              };
              (function(issue) {
                request.get(options, function(err, ret) {
                  if (err) {
                    console.log(err);
                  } else {
                    // we have the comments
                    for (var i=0; i<ret.body.length; i++) {
                      var comment = ret.body[i];
                      parseComment(repository, issue, comment, false);
                    }
                  }
                });
              })(issue);
            }
          }
        });
      });
      reply('OK');
    }});

server.route({
    method: 'GET',
    path:'/add_repo',
    handler: function (request, reply) {
      // serve form that suggests we add repos
      reply.file('add_repo.html');
    }
});

// Start the server
server.start();

<|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 routes = require('./routes/index');
var status = require('./routes/status');

var app = express();

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

// 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('/', routes);
app.use('/status', status);

// 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 handlers

// development error handler
// will print stacktrace
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
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>Add url2Host utility<commit_after>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 url = require('url');

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

var app = express();

// local
app.locals.url2Host = function(urlString) { return url.parse(urlString).host; };

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

// 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('/', routes);
app.use('/status', status);

// 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 handlers

// development error handler
// will print stacktrace
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
    });
  });
}

// production error handler
// no stacktraces leaked to user
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>"use strict";

const aws 		= require('aws-sdk');
const player		= require('play-sound')();
const util 		= require('util');
const readline		= require('readline');
const path		= require('path');
const fs 		= require('fs');
const exec		= require('child_process').exec;

const CMDLINE_AUTOPLAY		=	'defaults write com.apple.QuickTimePlayerX MGPlayMovieOnOpen 1';
const CMDLINE_AUTO 		=	'open -F ';
const LOG_TYPE			=	['[inf]','[err]','[war]'];
const LOG_INF			=	0;
const LOG_ERR			=	1;
const LOG_WAR			=	2;
const MEDIA_DIR			=	"media";
const CURR_DIR			=	".";
const CLICK 			= 	['single','double'];
const SINGLE 			=	0;
const DOUBLE 			=	1;

const EVT 			= ['SIGINT'];
const EVT_FS_SIGINT		= 0;
const SQS_OPTIONS		= 	{/* usr: iotButton */
				"accessKeyId"			: "",
			 	"secretAccessKey"		: "",
			 	"region"			: "eu-west-1"
					};

const SQS_RECEIVE_OPT	=	{
								"QueueUrl"				: "https://sqs.eu-west-1.amazonaws.com/?/?",
      							"MaxNumberOfMessages"	: 1
							};

const sqs 				=	new aws.SQS( SQS_OPTIONS );
const SQS_SLEEP			=	1000;

/**
 * func: deleteMessageSQSJSON
 * Desc: used as a simple way to construct JavaObjects that contain the relevant delete message instructions
 * params:
 *		msg JavaObject Of Type queued message
 *
 * returns:
 *		JavaObject as Type Of Delete Instruction.
 */
function deleteMessageSQSJSON ( msg ){
	return (
			{
				QueueUrl: SQS_RECEIVE_OPT.QueueUrl,
      			ReceiptHandle: msg.ReceiptHandle
			}
		);
}

function report_error( func, subject, message ){
	util.log (`${LOG_TYPE[LOG_ERR]}-[${func}]-[${subject}]::${message}`);
}

function report_info( func, subject, message ){
	util.log (`${LOG_TYPE[LOG_INF]}[${func}]-[${subject}]::${message}`);
}

function hasMessages ( data ){
	const func = "hasMessages";
	var bHasMessages = false
	try{
		bHasMessages = data.Messages.length >= 0;
	}catch(err){
		util.log (`[inf][${func}]-[No_Messages]::${JSON.stringify(data)}`);
	}
	return ( bHasMessages)
}

function cmdline ( cmd ){

	exec(cmd, function ( err, stdout ){
		const func = "exec";
		if(err){
			report_error(func, 'onErr',err);
		} else {
			report_info(func, 'OnEyes','Now showing');
		}
	});//end exec
}

// NOTE: open %s works on osx and windows. Not sure about lynx[%variant]
// TODO: enable auto play only works on osx

function playTune () {
	const func = "playTune";
	try{

		cmdline (CMDLINE_AUTO + path.join(CURR_DIR,MEDIA_DIR,'isabell.mp4'));
		player.play(path.join(CURR_DIR,MEDIA_DIR	,'single.mpeg'), function(err){
			const func = "play";
			if(err){
				report_error(func, 'onErr',err);
			} else {
				report_info(func, 'OnEars','can you hear me now? can you hear me now?');
			}
		});//end func:play
	} catch ( err ){
		report_error(func, 'onErr','aint nothing going-on');
	}
}

function isSingleClick ( messageBody ) {
	return ( whichClick(messageBody) == CLICK[SINGLE]) ;
}

function isDoubleClick ( messageBody ) {
	return ( whichClick(messageBody) == CLICK[DOUBLE]) ;
}

function whichClick ( messageBody ) {
	return ( (messageBody.clickType).trim().toLowerCase() );
}

/**
 *
 *
 *
 */
function receiveMessage() {
	const func = "receiveMessage";
  	report_info(func,'query_sqs',SQS_RECEIVE_OPT.QueueUrl);

	/*
	 * Invoke receiveMessage to check for new messages on our queue.
	 *
	 */
	sqs.receiveMessage(SQS_RECEIVE_OPT, function(err, data) {
  		const func = "sqs.receiveMessage";
		if (err){
    		report_error(func,'receiveMessage',err);
    	} else {
    		try{
    			if ( hasMessages(data) ){
	    			data.Messages.forEach(function(message) {
	    				// used this to look at the message structure
						//report_info(func,'Payload:Received',`Msg[${JSON.stringify(message.Body)}]`);
	    				report_info(func,'Payload:Received',`Msg[${message.MessageId}]`);

	    				var body = JSON.parse(message.Body);
						report_info(func,'Payload:Message.Body',`[0]-${body.serialNumber},Battery:${body.batteryVoltage},Click:${body.clickType}..Single[${isSingleClick(body)}] Double[${isDoubleClick(body)}]`);

	    				report_info(func,'Payload:Prepare to Delete',`Msg[${message.MessageId}]`);

	    				/*
	    				 * Invoke the delete Message API
	    				 *	 - construct delete message JavaObject using deleteMessageSQSJSON
	    				 */
	    				sqs.deleteMessage(deleteMessageSQSJSON(message), function(err, data) {
	    					const func = "sqs.deleteMessage";
	    					if (err){
	    						report_error(func,'On::Delete::!',err);
	    					} else {
	    						report_info(func,'On::Delete::Done',JSON.stringify(data));
	    						playTune();
	    					}
	    				});//end func: sqs.deleteMessage
		    		});//end forEach
	    		}//endif: hasMessages
	    	}catch ( err ){
	    		report_error(func,'data.Messages[!]',err);
	    	}
    	}//endif:err
  });//end sqs.receiveMessage
}//end func: receiveMessages

cmdline (CMDLINE_AUTOPLAY);

var button_click = setInterval (receiveMessage,SQS_SLEEP);

// Hook into the control-c... allows us to do some clean up...
var rl  = readline.createInterface( process.stdin, process.stdout);

 rl.on( EVT[EVT_FS_SIGINT], function ( stdin ){
	util.log(`control-c.... app stopping`);
	process.exit(0);
});

<commit_msg>IMP-001<commit_after>"use strict";

const aws 		= require('aws-sdk');
const player	= require('play-sound')();
const util 		= require('util');
const readline	= require('readline');
const path		= require('path');
const fs 		= require('fs');
const exec		= require('child_process').exec;

const DOTW				=	['sun','mon','tue','wed','thur','fri','sat'];
const CMDLINE_AUTOPLAY	=	'defaults write com.apple.QuickTimePlayerX MGPlayMovieOnOpen 1';
const CMDLINE_AUTO 		=	'open -F ';
const LOG_TYPE			=	['[inf]','[err]','[war]'];
const LOG_INF			=	0;
const LOG_ERR			=	1;
const LOG_WAR			=	2;
const MEDIA_DIR			=	"media";
const CURR_DIR			=	".";
const CLICK 			= 	['single','double'];
const SINGLE 			=	0;
const DOUBLE 			=	1;
const COMMA_DELIM		=	',';
const HYPHEN_DELIM		=	'-';
const EVT 				= ['SIGINT'];
const EVT_FS_SIGINT		= 0;
const WORKDAY_TRUE		= 99;

// IMP:[001] removed the security options and placed them in a json file.  Same format. Read in using aws.config.loadFromPath
//const SQS_OPTIONS		=
//
const AWS_CRED_FILE		= 'aws.cred.json';
const SQS_OPTIONS		= aws.config.loadFromPath ( path.join('.',AWS_CRED_FILE));

const SQS_RECEIVE_OPT	=	{
								"QueueUrl"				: "https://sqs.eu-west-1.amazonaws.com/381605567957/irl-iot-button-click",
      							"MaxNumberOfMessages"	: 1
							};

const sqs 				=	new aws.SQS( SQS_OPTIONS );
const SQS_SLEEP			=	1000;

var WorkingDayShedule	= {};
/**
 * func: deleteMessageSQSJSON
 * Desc: used as a simple way to construct JavaObjects that contain the relevant delete message instructions
 * params:
 *		msg JavaObject Of Type queued message
 *
 * returns:
 *		JavaObject as Type Of Delete Instruction.
 */
function deleteMessageSQSJSON ( msg ){
	return (
			{
				QueueUrl: SQS_RECEIVE_OPT.QueueUrl,
      			ReceiptHandle: msg.ReceiptHandle
			}
		);
}

//IMP[002] due to the costs involved, we only want the app to work on days we are going to be in the office.
function isTimeToWork ( startTime, endTime){
	const HH=0;
	const MM=1;
	const currentHH = parseInt(((new Date()).getHours()));
	//const currentMM = parseInt(((new Date()).getMinutes()));

	var start_time = startTime.split(':');
	var end_time   = endTime.split(':');

	return ( (currentHH >= parseInt(start_time[HH]) ) && (currentHH <= parseInt(end_time[HH]) ) );
}

function isTodayAWorkingDay( listOfWorkingDays ){
	var i = 0;
	for ( i =0 ; i<listOfWorkingDays.length ; i++){

		if (workingToday ( listOfWorkingDays[i].trim().toLowerCase() )) {
			//console.log(`checked : ${listOfWorkingDays[i].trim().toLowerCase()} - today is a working day!`);
			i=(WORKDAY_TRUE-1);//subtract 1, as the i++ in the loop will increment.
		}

	}
	//console.log(`value of i=${i} workingday:${i===99}`);
	return ( i===WORKDAY_TRUE);
}
function workingToday(  dayOfTheWeek ) {
	return ( dayOfTheWeek.trim().toLowerCase() === (nameOfToday()).trim().toLowerCase() ) ;
}
function nameOfToday (){
	return (DOTW[(new Date()).getDay()]);
}

function report_error( func, subject, message ){
	util.log (`${LOG_TYPE[LOG_ERR]}-[${func}]-[${subject}]::${message}`);
}

function report_info( func, subject, message ){
	util.log (`${LOG_TYPE[LOG_INF]}[${func}]-[${subject}]::${message}`);
}

function hasMessages ( data ){
	const func = "hasMessages";
	var bHasMessages = false
	try{
		bHasMessages = data.Messages.length >= 0;
	}catch(err){
		util.log (`[inf][${func}]-[No_Messages]::${JSON.stringify(data)}`);
	}
	return ( bHasMessages)
}

function cmdline ( cmd ){

	exec(cmd, function ( err, stdout ){
		const func = "exec";
		if(err){
			report_error(func, 'onErr',err);
		} else {
			report_info(func, 'OnEyes','Now showing');
		}
	});//end exec
}

// NOTE: open %s works on osx and windows. Not sure about lynx[%variant]
// TODO: enable auto play only works on osx

function playTune () {
	const func = "playTune";
	try{

		cmdline (CMDLINE_AUTO + path.join(CURR_DIR,MEDIA_DIR,'isabell.mp4'));
		player.play(path.join(CURR_DIR,MEDIA_DIR	,'single.mpeg'), function(err){
			const func = "play";
			if(err){
				report_error(func, 'onErr',err);
			} else {
				report_info(func, 'OnEars','can you hear me now? can you hear me now?');
			}
		});//end func:play
	} catch ( err ){
		report_error(func, 'onErr','aint nothing going-on');
	}
}

function isSingleClick ( messageBody ) {
	return ( whichClick(messageBody) == CLICK[SINGLE]) ;
}

function isDoubleClick ( messageBody ) {
	return ( whichClick(messageBody) == CLICK[DOUBLE]) ;
}

function whichClick ( messageBody ) {
	return ( (messageBody.clickType).trim().toLowerCase() );
}

/**
 *
 *
 *
 */
function receiveMessage() {
	const func = "receiveMessage";

  	/*
  	 * should I be working?
  	 * // Hacking!  just check and terminate if it's not a working day!
  	 */
  	 if ( ( (isTodayAWorkingDay(WorkingDayShedule))===false) && (isTimeToWork(WorkingHours[0],WorkingHours[1]) === false) ){
  	 	util.log(`No work on ${nameOfToday()}. The working shedule is:${WorkingDayShedule}`);
  	 	return;
  	 }
  	 report_info(func,'query_sqs',SQS_RECEIVE_OPT.QueueUrl);

	/*
	 * Invoke receiveMessage to check for new messages on our queue.
	 *
	 */
	sqs.receiveMessage(SQS_RECEIVE_OPT, function(err, data) {
  		const func = "sqs.receiveMessage";
		if (err){
    		report_error(func,'receiveMessage',err);
    	} else {
    		try{
    			if ( hasMessages(data) ){
	    			data.Messages.forEach(function(message) {
	    				// used this to look at the message structure
						//report_info(func,'Payload:Received',`Msg[${JSON.stringify(message.Body)}]`);
	    				report_info(func,'Payload:Received',`Msg[${message.MessageId}]`);

	    				var body = JSON.parse(message.Body);
						report_info(func,'Payload:Message.Body',`[0]-${body.serialNumber},Battery:${body.batteryVoltage},Click:${body.clickType}..Single[${isSingleClick(body)}] Double[${isDoubleClick(body)}]`);

	    				report_info(func,'Payload:Prepare to Delete',`Msg[${message.MessageId}]`);

	    				/*
	    				 * Invoke the delete Message API
	    				 *	 - construct delete message JavaObject using deleteMessageSQSJSON
	    				 */
	    				sqs.deleteMessage(deleteMessageSQSJSON(message), function(err, data) {
	    					const func = "sqs.deleteMessage";
	    					if (err){
	    						report_error(func,'On::Delete::!',err);
	    					} else {
	    						report_info(func,'On::Delete::Done',JSON.stringify(data));
	    						playTune();
	    					}
	    				});//end func: sqs.deleteMessage
		    		});//end forEach
	    		}//endif: hasMessages
	    	}catch ( err ){
	    		report_error(func,'data.Messages[!]',err);
	    	}
    	}//endif:err
  });//end sqs.receiveMessage
}//end func: receiveMessages

cmdline (CMDLINE_AUTOPLAY);

var WorkingDayShedule = process.argv[2].split(COMMA_DELIM);
var WorkingHours = process.argv[3].split(HYPHEN_DELIM);
//console.log(`${WorkingHours} - ${WorkingHours[0]} - ${WorkingHours[1]}`);

var button_click = setInterval (receiveMessage,SQS_SLEEP);

// Hook into the control-c... allows us to do some clean up...
var rl  = readline.createInterface( process.stdin, process.stdout);

 rl.on( EVT[EVT_FS_SIGINT], function ( stdin ){
	util.log(`control-c.... app stopping`);
	process.exit(0);
});

<|endoftext|>


<commit_before>export const createApp = (state) => {
  let willCallView = false
  let view

  const callView = () => {
    if (willCallView) return

    willCallView = true

    Promise.resolve().then(() => {
      willCallView = false

      if (view) {
        view(state)
      }
    })
  }

  return {
    render(v) {
      view = v

      callView()
    },
    set state(val) {
      state = val

      callView()
    },
    get state() {
      return state
    }
  }
}
<commit_msg>Render multiple views<commit_after>export const createApp = (state) => {
  let willCallView = false
  const views = []

  const callView = () => {
    if (willCallView) return

    willCallView = true

    Promise.resolve().then(() => {
      willCallView = false

      views.map((view) => view(state))
    })
  }

  return {
    render(v) {
      views.push(v)

      callView()
    },
    set state(val) {
      state = val

      callView()
    },
    get state() {
      return state
    }
  }
}
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var game = require('./routes/game');
var application = require('./routes/application');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var User = require('./models/User');
var Game = require('./models/Game');
var MongoStore = require('connect-mongo')(express);

app = express();
var server = http.createServer(app);
io = require('socket.io').listen(server);
request = require('request');

var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/test';
// database
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log("connected to mongodb");
});

// all environments
app.set('port', process.env.PORT || 3001);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon(path.join(__dirname, 'public/images/favicon.ico')));  // Our favicon
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('something super secret?'));
app.use(express.session({
  secret: 'something super secret?',
  store: new MongoStore({
    db: 'sessions'
  })
}));

//If we aren't in development, we're on heroku and need to use long polling
if ('development' != app.get('env')) {
  io.configure(function () {
    io.set("transports", ["xhr-polling"]);
    io.set("polling duration", 10);
  });
}

//builds breadcrumbs in nav bar
function buildBreadCrumbs(url) {
  var breadcrumbs = [];
  //splits url
  var url_bits = url.split("/");
  //url_bits[0] is always blank
  //check first part
  if (url_bits[1]) {
    //if it's 'games'...
    if (url_bits[1] == "games") {
      //push a link with the text "Games" leading to "/games/"
      breadcrumbs.push(["Games", "/games/"]);
      //check second part (if first part is "/games/", then second part would be game id)
      if (url_bits[2])
        //add game id
        breadcrumbs.push([url_bits[2].substring(0,8)+"...", "/games/"+url_bits[2]]);
    }
  }
  return breadcrumbs;
}

//run before every request is handled
app.configure(function(){
  app.use(function(req, res, next){
    res.locals.breadcrumbs = buildBreadCrumbs(req.url);
    var id = mongoose.Types.ObjectId(req.session.user_id);
    User.findById(id, function(err, cur_user) {
      //I don't know what this does, I added braces
      if (cur_user != undefined){
        res.locals.current_user = cur_user;
      }
      next();
    });
  });
});

app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

function checkAuth(req, res, next) {
  if (!req.session.user_id) {
    res.redirect('/login');
  } else {
    next();
  }
}

app.get('/login', application.login);
app.post('/attempt_login', application.attempt_login);
app.post('/create_account', application.create_account);
app.get('/logout', application.logout);

//These actions are protected by login system, checkAuth
app.get('/', checkAuth, routes.index);
app.post('/games/game_list', checkAuth, game.game_list);
app.get('/games', checkAuth, routes.index);
app.get('/super_spectator', checkAuth, game.super_spectator);
app.get('/users', checkAuth, user.list);
app.post('/games/create', checkAuth, game.create_game);
app.get('/games/:id', checkAuth, game.show);
app.post('/games/:id/join', checkAuth, game.join);
app.post('/games/:id/move', checkAuth, game.move);
app.post('/games/:id/info', checkAuth, game.info);
app.post('/games/:id/check', checkAuth, game.check);
app.get('/games/:id/leave', checkAuth, game.leave);
app.get('/games/:id/board', checkAuth, game.board);
app.post('/games/:id/message', checkAuth, game.message);
app.post('/games/:id/request_move', checkAuth, game.request_move);
app.get('/users/:name', checkAuth, user.user_page);

server.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>Session ish<commit_after>
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var game = require('./routes/game');
var application = require('./routes/application');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var User = require('./models/User');
var Game = require('./models/Game');
var MongoStore = require('connect-mongo')(express);

app = express();
var server = http.createServer(app);
io = require('socket.io').listen(server);
request = require('request');

var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/test';
// database
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log("connected to mongodb");
});

// all environments
app.set('port', process.env.PORT || 3001);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon(path.join(__dirname, 'public/images/favicon.ico')));  // Our favicon
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('something super secret?'));
app.use(express.session({
  secret: 'something super secret?',
  store: new MongoStore({
    url: mongoUri,
    mongoose_connection: db
  })
}));

//If we aren't in development, we're on heroku and need to use long polling
if ('development' != app.get('env')) {
  io.configure(function () {
    io.set("transports", ["xhr-polling"]);
    io.set("polling duration", 10);
  });
}

//builds breadcrumbs in nav bar
function buildBreadCrumbs(url) {
  var breadcrumbs = [];
  //splits url
  var url_bits = url.split("/");
  //url_bits[0] is always blank
  //check first part
  if (url_bits[1]) {
    //if it's 'games'...
    if (url_bits[1] == "games") {
      //push a link with the text "Games" leading to "/games/"
      breadcrumbs.push(["Games", "/games/"]);
      //check second part (if first part is "/games/", then second part would be game id)
      if (url_bits[2])
        //add game id
        breadcrumbs.push([url_bits[2].substring(0,8)+"...", "/games/"+url_bits[2]]);
    }
  }
  return breadcrumbs;
}

//run before every request is handled
app.configure(function(){
  app.use(function(req, res, next){
    res.locals.breadcrumbs = buildBreadCrumbs(req.url);
    var id = mongoose.Types.ObjectId(req.session.user_id);
    User.findById(id, function(err, cur_user) {
      //I don't know what this does, I added braces
      if (cur_user != undefined){
        res.locals.current_user = cur_user;
      }
      next();
    });
  });
});

app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

function checkAuth(req, res, next) {
  if (!req.session.user_id) {
    res.redirect('/login');
  } else {
    next();
  }
}

app.get('/login', application.login);
app.post('/attempt_login', application.attempt_login);
app.post('/create_account', application.create_account);
app.get('/logout', application.logout);

//These actions are protected by login system, checkAuth
app.get('/', checkAuth, routes.index);
app.post('/games/game_list', checkAuth, game.game_list);
app.get('/games', checkAuth, routes.index);
app.get('/super_spectator', checkAuth, game.super_spectator);
app.get('/users', checkAuth, user.list);
app.post('/games/create', checkAuth, game.create_game);
app.get('/games/:id', checkAuth, game.show);
app.post('/games/:id/join', checkAuth, game.join);
app.post('/games/:id/move', checkAuth, game.move);
app.post('/games/:id/info', checkAuth, game.info);
app.post('/games/:id/check', checkAuth, game.check);
app.get('/games/:id/leave', checkAuth, game.leave);
app.get('/games/:id/board', checkAuth, game.board);
app.post('/games/:id/message', checkAuth, game.message);
app.post('/games/:id/request_move', checkAuth, game.request_move);
app.get('/users/:name', checkAuth, user.user_page);

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