<commit_before>/**
 * War Server
 * Author: Michael Cebrian
 * Date: 09/19/2014
 * Description: Web server that allows connected users to play War.
 **/

var express = require('express');
var app = express();
var port = process.env.PORT || 80;
var host = process.env.IP || 'mcebrian.com';
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var passportSocketIo = require('passport.socketio');
var sessionSocketIo = require('session.socket.io');
var favicon = require('serve-favicon');
var server = require('http').createServer(app);
var subdomain = require('express-subdomain');

// Mongoose Settings
var dbPort = 27017;
var configDB = require('./config/database')(host, dbPort);
mongoose.connect(configDB.url);

// Express extensions
var sessionInfo = require('./config/session');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var mongoStore = require('connect-mongo')(session);
var sessionConf = require('./config/session');

// passport configuration
require('./config/passport')(passport);

// Set up Express

var dbStore = new mongoStore({ mongoose_connection: mongoose.connections[0] });
app.set('view engine', 'ejs');
var sessionHandler = session({
  name: sessionInfo.name,
  secret: sessionInfo.secret,
  store: dbStore,
  cookie: {}
});

app.use(subdomain('war', app));
app.use(morgan('dev'));
app.use(cookieParser(sessionInfo.secret));
app.use(bodyParser());
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(express.static(__dirname + '/public'));
app.use(sessionHandler);
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());

// Add routes
require('./config/routes.js')(app, passport);

// Setup Socket.io
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
io.use(passportSocketIo.authorize({
  passport: passport,
  cookieParser: cookieParser,
  key: sessionInfo.name,
  secret: sessionInfo.secret,
  store: dbStore,
  success: function(data, accept) {
    console.log("successful socket.io auth.");
    accept();
  },
  fail: function(data, message, error, accept) {
    if (error) {
      accept(new Error(message));
    }
    console.log("failed to connect to socket.io: " + message);
    //accept(null, false);
  }
}));

require('./war/WarServer')(io);

// Everything is set up now, start listening for connections
server.listen(port);

console.log(new Date().toString(),'\nServer listening on port: ' + port);
<commit_msg>subdomain<commit_after>/**
 * War Server
 * Author: Michael Cebrian
 * Date: 09/19/2014
 * Description: Web server that allows connected users to play War.
 **/

var express = require('express');
var app = express();
var port = process.env.PORT || 80;
var host = process.env.IP || 'mcebrian.com';
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var passportSocketIo = require('passport.socketio');
var sessionSocketIo = require('session.socket.io');
var favicon = require('serve-favicon');
var server = require('http').createServer(app);
var subdomain = require('express-subdomain');

// Mongoose Settings
var dbPort = 27017;
var configDB = require('./config/database')(host, dbPort);
mongoose.connect(configDB.url);

// Express extensions
var sessionInfo = require('./config/session');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var mongoStore = require('connect-mongo')(session);
var sessionConf = require('./config/session');

// passport configuration
require('./config/passport')(passport);

// Set up Express

var dbStore = new mongoStore({ mongoose_connection: mongoose.connections[0] });
app.set('view engine', 'ejs');
var sessionHandler = session({
  name: sessionInfo.name,
  secret: sessionInfo.secret,
  store: dbStore,
  cookie: {}
});

app.use(subdomain('war', app));
app.use(morgan('dev'));
app.use(cookieParser(sessionInfo.secret));
app.use(bodyParser());
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(express.static(__dirname + '/public'));
app.use(sessionHandler);
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());

// Add routes
require('./config/routes.js')(app, passport);

// Setup Socket.io
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
io.use(passportSocketIo.authorize({
  passport: passport,
  cookieParser: cookieParser,
  key: sessionInfo.name,
  secret: sessionInfo.secret,
  store: dbStore,
  success: function(data, accept) {
    console.log("successful socket.io auth.");
    accept();
  },
  fail: function(data, message, error, accept) {
    if (error) {
      accept(new Error(message));
    }
    console.log("failed to connect to socket.io: " + message);
    //accept(null, false);
  }
}));

require('./war/WarServer')(io);

// Everything is set up now, start listening for connections
server.listen(port, host);

console.log(new Date().toString(),'\nServer listening on port: ' + port);
<|endoftext|>


<commit_before>"use strict";
var http = require("http");
var increasePrefix = require("./increase-prefix");
var keyRange = require("./key-range");

function renderUrl(key) {
    return "http://" + (process.argv[3] ||  "localhost") + "/" + key.replace("!", "");
}

function internalServerError(res) {
    res.statusCode = 500;
    res.end("Internal Server Error");
}

function notFound(res) {
    res.statusCode = 404;
    res.end("Not Found");
}

function redirectTo(res, url) {
    res.writeHead(301, {
        'Location': url
    });
    res.end();
}

function addNewKeys(prefix) {
    if (!prefix) {
        prefix = "0";
    } else {
        prefix = (parseInt(prefix, 36) + 1).toString(36);
    }

    return {
        prefix: prefix,
        keys: keyRange(prefix)
    };
}
module.exports = function server(prefix, keys, db) {
    function insert(url, cb) {
        var batch = db.batch();

        if (keys.length === 0) {
            var newKeys = addNewKeys(prefix);
            keys = newKeys.keys;
            prefix = newKeys.prefix;
            batch.put("!!prefix", prefix);
        }

        var key = keys.pop();
        batch.put(key, url)
            .put(url, key)
            .write(function (err) {
                cb(err, key);
            });
    }

    function handlePost(req, res) {
        var body = "";
        req.on("data", function (data) {
            body += data.toString();
        }).on("end", function () {
            db.get(body, function (err, data) {
                if (err && err.name === "NotFoundError") {
                    return insert(body, function (err, key) {
                        if (err) console.error(err);
                        res.end(renderUrl(key));
                    });
                }

                if (err) {
                    console.error(err);
                    return internalServerError(res);
                }

                if (data) {
                    return res.end(renderUrl(data));
                }

            });
        });

    }

    function handleGet(req, res) {
        var key = req.url.split("/")[1];
        db.get("!" + key, function (err, data) {
            if (err) {
                if (err.name == "NotFoundError") {
                    return notFound(res);
                }

                console.error(err);
                return internalServerError(res);
            }

            redirectTo(res, data);
        });
    }

    return http.createServer(function (req, res) {
        if (req.method == "POST") {
            return handlePost(req, res);
        }

        if (req.url == "/") {
            res.writeHead("Content-type", "text/html");
            return fs.createReadStream("./index.html").pipe(res);
        }

        handleGet(req, res);
    });
}

<commit_msg>add missing dependency<commit_after>"use strict";
var http = require("http");
var fs = require("fs");
var increasePrefix = require("./increase-prefix");
var keyRange = require("./key-range");

function renderUrl(key) {
    return "http://" + (process.argv[3] ||  "localhost") + "/" + key.replace("!", "");
}

function internalServerError(res) {
    res.statusCode = 500;
    res.end("Internal Server Error");
}

function notFound(res) {
    res.statusCode = 404;
    res.end("Not Found");
}

function redirectTo(res, url) {
    res.writeHead(301, {
        'Location': url
    });
    res.end();
}

function addNewKeys(prefix) {
    if (!prefix) {
        prefix = "0";
    } else {
        prefix = (parseInt(prefix, 36) + 1).toString(36);
    }

    return {
        prefix: prefix,
        keys: keyRange(prefix)
    };
}
module.exports = function server(prefix, keys, db) {
    function insert(url, cb) {
        var batch = db.batch();

        if (keys.length === 0) {
            var newKeys = addNewKeys(prefix);
            keys = newKeys.keys;
            prefix = newKeys.prefix;
            batch.put("!!prefix", prefix);
        }

        var key = keys.pop();
        batch.put(key, url)
            .put(url, key)
            .write(function (err) {
                cb(err, key);
            });
    }

    function handlePost(req, res) {
        var body = "";
        req.on("data", function (data) {
            body += data.toString();
        }).on("end", function () {
            db.get(body, function (err, data) {
                if (err && err.name === "NotFoundError") {
                    return insert(body, function (err, key) {
                        if (err) console.error(err);
                        res.end(renderUrl(key));
                    });
                }

                if (err) {
                    console.error(err);
                    return internalServerError(res);
                }

                if (data) {
                    return res.end(renderUrl(data));
                }

            });
        });

    }

    function handleGet(req, res) {
        var key = req.url.split("/")[1];
        db.get("!" + key, function (err, data) {
            if (err) {
                if (err.name == "NotFoundError") {
                    return notFound(res);
                }

                console.error(err);
                return internalServerError(res);
            }

            redirectTo(res, data);
        });
    }

    return http.createServer(function (req, res) {
        if (req.method == "POST") {
            return handlePost(req, res);
        }

        if (req.url == "/") {
            res.writeHead("Content-type", "text/html");
            return fs.createReadStream("./index.html").pipe(res);
        }

        handleGet(req, res);
    });
}

<|endoftext|>


<commit_before>#!/usr/bin/env node
var http  = require('http')
  , fs    = require('fs')
  , path  = require('path')
  , mime  = require('mime')
  , cache = {};

function send404(response) {
  response.writeHead(404, {'Content-Type': 'text/plain'});
  response.write('Error 404: resource not found.');
  response.end();
}

function serveStatic(response, cache, absPath) {
  if (cache[absPath]) {
    response.writeHead('content-type', mime.lookup(path.basename(absPath)));
    response.end(cache[absPath]);
  } else {
    path.exists(absPath, function(exists) {
      if (exists) {
        fs.readFile(absPath, function(err, data) {
          cache[absPath] = data;
          response.writeHead('content-type', mime.lookup(path.basename(absPath)));
          response.end(data);
        });
      } else {
        send404(response);
      }
    });
  }
}

var server = http.createServer(function(request, response) {
  var filePath = false;

  if (request.url == '/') {
    filePath = 'public/index.html';
  } else {
    filePath = 'public' + request.url;
  }

  if (!filePath) {
    send404(response);
  } else {
    var absPath = './' + filePath;
    serveStatic(response, cache, absPath);
  }
});

server.listen(3000, function() {
  console.log("Server listening on port 3000.");
});

var io = require('socket.io').listen(server)
  , guestNumber = 1
  , nickNames = {}
  , namesUsed = []
  , name
  , nameIndex;

io.set('log level', 1);

io.sockets.on('connection', function (socket) {
  socket.join('Lobby');
  socket.emit('joinResult', {room: 'Lobby'});

  name = 'Guest' + guestNumber;
  nickNames[socket.id] = name;
  socket.emit('nameResult', {
    success: true,
    name: name
  });
  namesUsed.push(name);
  guestNumber += 1;

  socket.on('message', function (message) {
    socket.broadcast.to(message.room).emit('message', {
      text: nickNames[socket.id] + ': ' + message.text
    });
  });

  socket.on('nameAttempt', function(name) {
    if (name.indexOf('Guest') == 0) {
      socket.emit('nameResult', {
        success: false,
        message: 'Names cannot begin with "Guest".'
      });
    } else {
      if (namesUsed.indexOf(name) == -1) {
        namesUsed.push(name);
        nickNames[socket.id] = name;
        socket.emit('nameResult', {
          success: true,
          name: name
        });
      } else {
        socket.emit('nameResult', {
          success: false,
          message: 'That name is already in use.'
        });
      }
    }
  });

  socket.on('join', function(room) {
    socket.leave(room.previousRoom);
    socket.join(room.newRoom);
    socket.emit('joinResult', {room: room.newRoom});
  });

  socket.on('rooms', function() {
    socket.emit('rooms', io.sockets.manager.rooms);
  });

  socket.on('disconnect', function() {
    nameIndex = namesUsed.indexOf(nickNames[socket.id]);
    delete namesUsed[nameIndex];
    delete nickNames[socket.id];
  });
});
<commit_msg>Tiny style tweak.<commit_after>#!/usr/bin/env node
var http  = require('http')
  , fs    = require('fs')
  , path  = require('path')
  , mime  = require('mime')
  , cache = {};

function send404(response) {
  response.writeHead(404, {'Content-Type': 'text/plain'});
  response.write('Error 404: resource not found.');
  response.end();
}

function serveStatic(response, cache, absPath) {
  if (cache[absPath]) {
    response.writeHead(
      'content-type',
      mime.lookup(path.basename(absPath))
    );
    response.end(cache[absPath]);
  } else {
    path.exists(absPath, function(exists) {
      if (exists) {
        fs.readFile(absPath, function(err, data) {
          cache[absPath] = data;
          response.writeHead(
            'content-type',
            mime.lookup(path.basename(absPath))
          );
          response.end(data);
        });
      } else {
        send404(response);
      }
    });
  }
}

var server = http.createServer(function(request, response) {
  var filePath = false;

  if (request.url == '/') {
    filePath = 'public/index.html';
  } else {
    filePath = 'public' + request.url;
  }

  if (!filePath) {
    send404(response);
  } else {
    var absPath = './' + filePath;
    serveStatic(response, cache, absPath);
  }
});

server.listen(3000, function() {
  console.log("Server listening on port 3000.");
});

var io = require('socket.io').listen(server)
  , guestNumber = 1
  , nickNames = {}
  , namesUsed = []
  , name
  , nameIndex;

io.set('log level', 1);

io.sockets.on('connection', function (socket) {
  socket.join('Lobby');
  socket.emit('joinResult', {room: 'Lobby'});

  name = 'Guest' + guestNumber;
  nickNames[socket.id] = name;
  socket.emit('nameResult', {
    success: true,
    name: name
  });
  namesUsed.push(name);
  guestNumber += 1;

  socket.on('message', function (message) {
    socket.broadcast.to(message.room).emit('message', {
      text: nickNames[socket.id] + ': ' + message.text
    });
  });

  socket.on('nameAttempt', function(name) {
    if (name.indexOf('Guest') == 0) {
      socket.emit('nameResult', {
        success: false,
        message: 'Names cannot begin with "Guest".'
      });
    } else {
      if (namesUsed.indexOf(name) == -1) {
        namesUsed.push(name);
        nickNames[socket.id] = name;
        socket.emit('nameResult', {
          success: true,
          name: name
        });
      } else {
        socket.emit('nameResult', {
          success: false,
          message: 'That name is already in use.'
        });
      }
    }
  });

  socket.on('join', function(room) {
    socket.leave(room.previousRoom);
    socket.join(room.newRoom);
    socket.emit('joinResult', {room: room.newRoom});
  });

  socket.on('rooms', function() {
    socket.emit('rooms', io.sockets.manager.rooms);
  });

  socket.on('disconnect', function() {
    nameIndex = namesUsed.indexOf(nickNames[socket.id]);
    delete namesUsed[nameIndex];
    delete nickNames[socket.id];
  });
});
<|endoftext|>


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

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

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

  // variables

  // the current GameTime (is updated on restart)
  var time;

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

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

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

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

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

    // shuffle the array
    shuffle(roleArray);

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

    return result;
  }

  /**
   * Closes the previous night and starts the new day.
   * @param number the current number of the day that just started
   */
  function startDay(number) {

  }

  /**
   * Closes the day and starts the night.
   * @param number the current number of the day
   */
  function startNight(number) {

  }

  /**
   * Will be called when the day changes from night to day.
   * (or when a new game has been started)
   */
  function onTimeChanged() {
    // getting the time
    var now = new Date();

    // starting new timer
    var nextChange = time.getNextChange(now);
    var delay = nextChange.getTime() - now.getTime();
    Timer.cancel('onTimeChanged');
    Timer.set(delay, 'onTimeChanged');

    // calling startDay/startNight
    var number = time.getNumber(now);
    if (time.isDay(now)) {
      startDay(number);
    } else {
      startNight(number);
    }
  }

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

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

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

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

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

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

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

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

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

  exports.onTimeChanged = onTimeChanged;

}());
<commit_msg>Add creation of votings on day start/end<commit_after>(function () {
  'use strict';

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

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

  // variables

  // the current GameTime (is updated on restart)
  var time;

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

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

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

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

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

    // shuffle the array
    shuffle(roleArray);

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

    return result;
  }

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

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

  /**
   * Closes the previous night and starts the new day.
   * @param number the current number of the day that just started
   */
  function startDay(number) {
    // start a new vote
    var votingId = 'day' + number;
    createVoting(votingId, Plugin.userIds());
  }

  /**
   * Closes the day and starts the night.
   * @param number the current number of the day
   */
  function startNight(number) {
    // start a new vote
    var votingId = 'night' + number;
    var werewolves = usersWithRole(Constants.roles.WEREWOLF);
    createVoting(votingId, Plugin.userIds());
  }

  /**
   * Will be called when the day changes from night to day.
   * (or when a new game has been started)
   */
  function onTimeChanged() {
    // getting the time
    var now = new Date();

    // starting new timer
    var nextChange = time.getNextChange(now);
    var delay = nextChange.getTime() - now.getTime();
    Timer.cancel('onTimeChanged');
    Timer.set(delay, 'onTimeChanged');

    // calling startDay/startNight
    var number = time.getNumber(now);
    if (time.isDay(now)) {
      startDay(number);
    } else {
      startNight(number);
    }
  }

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

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

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

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

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

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

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

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

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

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

  exports.onTimeChanged = onTimeChanged;

  /* The rpc calls */

  /**
   * Lets the sending user vote.
   *
   */
  exports.vote = function (votingId, user) {

  };

}());
<|endoftext|>


<commit_before>'use strict';

var http = require('http');
var teapot = require('./');

var server = http.createServer(teapot);

server.listen(function () {
  console.log('Serer is running, open http://localhost:'
    + server.address().port + ' in your browser');
});
<commit_msg>Fix typo<commit_after>'use strict';

var http = require('http');
var teapot = require('./');

var server = http.createServer(teapot);

server.listen(function () {
  console.log('Server is running, open http://localhost:'
    + server.address().port + ' in your browser');
});
<|endoftext|>


<commit_before>var sharejs = require("share").server,
    express = require("express"),
    app = express();

app.use(express.static(__dirname + "/node_modules/marked/lib"));
app.use(express.static(__dirname + "/public"));

app.get("/:page?", function(req, res) {
  var page = req.params.page || "index";
  res.render("index.hjs", { page: page });
});

sharejs.attach(app, {
  db: { type: "redis" }
});

app.listen(3000);
<commit_msg>Add logger<commit_after>var sharejs = require("share").server,
    express = require("express"),
    app = express();

app.use(express.logger());
app.use(express.static(__dirname + "/node_modules/marked/lib"));
app.use(express.static(__dirname + "/public"));

app.get("/:page?", function(req, res) {
  var page = req.params.page || "index";
  res.render("index.hjs", { page: page });
});

sharejs.attach(app, {
  db: { type: "redis" }
});

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


<commit_before>var celery = Npm.require('node-celery');
var Future = Npm.require('fibers/future');

/**
 * A dictionary of CeleryClients
 * @type {Object}
 */
CeleryClients = {};

/**
 * Creates a new `CeleryClient` and stores it in `CeleryClients`
 * @param name
 * @constructor
 */
CeleryClient = function (name){
  this._name = name;
  this._connected = false;
  CeleryClients[this._name] = this;
};

_.extend(CeleryClient.prototype, {
  /**
   * Connects synchronously, proxies `conf` through to celery.createClient
   *
   * @param {Object} conf
   * @param {String} [conf.BROKER_URL='amqp://']
   * @param {String} [conf.RESULT_BACKEND]
   * @param {String} [conf.DEFAULT_QUEUE='celery']
   * @param {String} [conf.DEFAULT_EXCHANGE='']
   * @param {String} [conf.DEFAULT_EXCHANGE_TYPE='direct']
   * @param {String} [conf.DEFAULT_ROUTING_KEY='celery']
   * @param {String} [conf.RESULT_EXCHANGE='celeryresults']
   * @param {String} [conf.EVENT_EXCHANGE='celeryev']
   * @param {Boolean} [conf.SEND_TASK_SENT_EVENT=false]
   * @param {Number} [conf.TASK_RESULT_EXPIRES=86400000]
   * @param {Object} [conf.ROUTES={}]
   *
   * @throws Error
   *
   * @returns {Boolean}
   */
  connect: function(conf){
    var _this = this,
      future = new Future();

    this._client = celery.createClient(conf);

    this._client.on('connect', function CeleryClient_connect(){
      debug_client(_this._name, 'connected');
      _this._connected = true;
      future.return(true);
    });

    this._client.on('error', function CeleryClient_error(err){
      debug_client(_this._name, 'connection error', err);
      future.throw(err);
    });

    this._client.on('end', function CeleryClient_end(){
      debug_client(_this._name, 'connection closed');
      _this._connected = false;
    });

    return future.wait()
  },

  /**
   * Calls a Celery Task, returning futures for the result.
   *
   * @param {String} method
   * @param {Array} args
   * @param {Boolean} [trackStarted=false] if true, will return two futures, [0] for task started, and [1] for the result.
   * @returns {Future|Future[]}
   */
  call: function(method, args, trackStarted){
    var _this = this,
        result = new Future(),
        started, celery_result;

    // provide a separate `Future` if `trackStarted` is provided
    if (!!trackStarted){
      started = new Future();
    }

    // check that the client is currently connected.
    if (!this._connected){
      // causes both `started` & `result` to throw
      started && result.proxy(started);

      result.throw(new Error(debug_call_stmt(_this._name, method, null, "Call failed. Celery isn't connected")));
    } else {
      // call the method on the actual `client`
      celery_result = this._client.call(method, args);

      debug_call(this._name, method, celery_result.taskid, 'called');

      // register event handlers for failure
      celery_result.on('failure', CeleryClient_call_onError);
      celery_result.on('revoked', CeleryClient_call_onError);
      celery_result.on('rejected', CeleryClient_call_onError);
      celery_result.on('ignored', CeleryClient_call_onError);

      // register event handler for `started`
      started && celery_result.on('started', CeleryClient_call_onStarted);

      // register event handler for `success`
      celery_result.on('success', CeleryClient_call_onSuccess);
    }

    if (started){
      return [started, result];
    } else {
      return result;
    }

    function CeleryClient_call_onError(message){
      debug_call(_this._name, method, celery_result.taskid, "Call failed [" + message.status + "]", message.traceback);
      // only propagate the error to `started` if it hasn't resolved.
      if (started && !started.isResolved()){
        result.proxy(started);
      }

      result.throw(new Error(debug_call_stmt(_this._name, method, null, "Call failed [" + message.status + "]")));
    }

    function CeleryClient_call_onStarted(){
      debug_call(_this._name, method, celery_result.taskid, "Started");
      if (started.isResolved()) return;
      started.return(true);
    }

    function CeleryClient_call_onSuccess(message){
      // if `started` wasn't resolved -
      if (started && !started.isResolved()){
        debug_call(_this._name, method, celery_result.taskid, "Started (Warning: `started` was event forced)");
        started.return(true);
      }
      debug_call(_this._name, method, celery_result.taskid, "Success", message.result);
      result.return(message.result)
    }
  }
});

// debug code
var debug = function(){};
var debug_client = function(client_name, message){};
var debug_call = function(client_name, method_name, task_id, message){};
var debug_call_stmt = function(client_name, method_name, task_id, message){
  return 'CeleryClient[' + client_name +  ']#call(' + JSON.stringify(method_name) + ')[task_id:' + JSON.stringify(task_id) +'] - ' + message
};

if (!!process.env['METEOR_CELERY_DEBUG']){
  debug = function(){
    console.log.apply(console, arguments);
  };
  debug_client = function(client_name, message){
    var log_message = 'CeleryClient[' + client_name +  '] - ' + message,
      args = [].slice.call(arguments, 2);
    args.unshift(log_message);
    console.log.apply(console, args);
  };
  debug_call = function(client_name, method_name, task_id, message){
    var log_message = debug_call_stmt(client_name, method_name, task_id, message),
      args = [].slice.call(arguments, 4);
    args.unshift(log_message);
    console.log.apply(console, args);
  };
}
<commit_msg>Check that the future isn't already resolved when reporting connection events<commit_after>var celery = Npm.require('node-celery');
var Future = Npm.require('fibers/future');

/**
 * A dictionary of CeleryClients
 * @type {Object}
 */
CeleryClients = {};

/**
 * Creates a new `CeleryClient` and stores it in `CeleryClients`
 * @param name
 * @constructor
 */
CeleryClient = function (name){
  this._name = name;
  this._connected = false;
  CeleryClients[this._name] = this;
};

_.extend(CeleryClient.prototype, {
  /**
   * Connects synchronously, proxies `conf` through to celery.createClient
   *
   * @param {Object} conf
   * @param {String} [conf.BROKER_URL='amqp://']
   * @param {String} [conf.RESULT_BACKEND]
   * @param {String} [conf.DEFAULT_QUEUE='celery']
   * @param {String} [conf.DEFAULT_EXCHANGE='']
   * @param {String} [conf.DEFAULT_EXCHANGE_TYPE='direct']
   * @param {String} [conf.DEFAULT_ROUTING_KEY='celery']
   * @param {String} [conf.RESULT_EXCHANGE='celeryresults']
   * @param {String} [conf.EVENT_EXCHANGE='celeryev']
   * @param {Boolean} [conf.SEND_TASK_SENT_EVENT=false]
   * @param {Number} [conf.TASK_RESULT_EXPIRES=86400000]
   * @param {Object} [conf.ROUTES={}]
   *
   * @throws Error
   *
   * @returns {Boolean}
   */
  connect: function(conf){
    var _this = this,
      future = new Future();

    this._client = celery.createClient(conf);

    this._client.on('connect', function CeleryClient_connect(){
      debug_client(_this._name, 'connected');
      _this._connected = true;
      if (!future.isResolved()){
        future.return(true);
      }
    });

    this._client.on('error', function CeleryClient_error(err){
      debug_client(_this._name, 'connection error', err);
      if (!future.isResolved()){
        future.throw(err);
      }
    });

    this._client.on('end', function CeleryClient_end(){
      debug_client(_this._name, 'connection closed');
      _this._connected = false;
    });

    return future.wait()
  },

  /**
   * Calls a Celery Task, returning futures for the result.
   *
   * @param {String} method
   * @param {Array} args
   * @param {Boolean} [trackStarted=false] if true, will return two futures, [0] for task started, and [1] for the result.
   * @returns {Future|Future[]}
   */
  call: function(method, args, trackStarted){
    var _this = this,
        result = new Future(),
        started, celery_result;

    // provide a separate `Future` if `trackStarted` is provided
    if (!!trackStarted){
      started = new Future();
    }

    // check that the client is currently connected.
    if (!this._connected){
      // causes both `started` & `result` to throw
      started && result.proxy(started);

      result.throw(new Error(debug_call_stmt(_this._name, method, null, "Call failed. Celery isn't connected")));
    } else {
      // call the method on the actual `client`
      celery_result = this._client.call(method, args);

      debug_call(this._name, method, celery_result.taskid, 'called');

      // register event handlers for failure
      celery_result.on('failure', CeleryClient_call_onError);
      celery_result.on('revoked', CeleryClient_call_onError);
      celery_result.on('rejected', CeleryClient_call_onError);
      celery_result.on('ignored', CeleryClient_call_onError);

      // register event handler for `started`
      started && celery_result.on('started', CeleryClient_call_onStarted);

      // register event handler for `success`
      celery_result.on('success', CeleryClient_call_onSuccess);
    }

    if (started){
      return [started, result];
    } else {
      return result;
    }

    function CeleryClient_call_onError(message){
      debug_call(_this._name, method, celery_result.taskid, "Call failed [" + message.status + "]", message.traceback);
      // only propagate the error to `started` if it hasn't resolved.
      if (started && !started.isResolved()){
        result.proxy(started);
      }

      result.throw(new Error(debug_call_stmt(_this._name, method, null, "Call failed [" + message.status + "]")));
    }

    function CeleryClient_call_onStarted(){
      debug_call(_this._name, method, celery_result.taskid, "Started");
      if (started.isResolved()) return;
      started.return(true);
    }

    function CeleryClient_call_onSuccess(message){
      // if `started` wasn't resolved -
      if (started && !started.isResolved()){
        debug_call(_this._name, method, celery_result.taskid, "Started (Warning: `started` was event forced)");
        started.return(true);
      }
      debug_call(_this._name, method, celery_result.taskid, "Success", message.result);
      result.return(message.result)
    }
  }
});

// debug code
var debug = function(){};
var debug_client = function(client_name, message){};
var debug_call = function(client_name, method_name, task_id, message){};
var debug_call_stmt = function(client_name, method_name, task_id, message){
  return 'CeleryClient[' + client_name +  ']#call(' + JSON.stringify(method_name) + ')[task_id:' + JSON.stringify(task_id) +'] - ' + message
};

if (!!process.env['METEOR_CELERY_DEBUG']){
  debug = function(){
    console.log.apply(console, arguments);
  };
  debug_client = function(client_name, message){
    var log_message = 'CeleryClient[' + client_name +  '] - ' + message,
      args = [].slice.call(arguments, 2);
    args.unshift(log_message);
    console.log.apply(console, args);
  };
  debug_call = function(client_name, method_name, task_id, message){
    var log_message = debug_call_stmt(client_name, method_name, task_id, message),
      args = [].slice.call(arguments, 4);
    args.unshift(log_message);
    console.log.apply(console, args);
  };
}
<|endoftext|>


<commit_before>import path from 'path';
import passport from 'passport';
import express from 'express';

require('dotenv').config();

const session = require('express-session');

const GoogleStrategy = require('passport-google-oauth20').Strategy;

const port = process.env.PORT || 5000;
const app = express();
app.use(passport.initialize());
app.use(passport.session());
app.use(session({
  secret: 'keyboard cat',
  key: 'user_sid',
  resave: false,
  saveUninitialized: false,
  cookie: { expires: 600000 },
}));
app.use(express.static('public'));
// app.use(bodyParser.urlencoded({ extended: true }));
// app.use(bodyParser.json());
passport.serializeUser((user, done) => {
  done(null, user);
});

passport.deserializeUser((obj, done) => {
  done(null, obj);
});

passport.use(new GoogleStrategy({
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: process.env.CALLBACK_URL,
},
  (accessToken, refreshToken, profile, cb) =>
    // User.findOrCreate({ googleId: profile.id }, function (err, user) {
      // process.nextTick(function () {
     cb(null, profile)
    // });
    // return cb(null, profile);
    // });
  ,
));

app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile'] }));

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/' }),
  (req, res) => {
    console.log('userinfo', req.user);
    // Successful authentication, redirect home.
    res.redirect('/home');
  });

app.get('/logout', (req, res) => {
  req.logOut();
  res.clearCookie('user_sid');
  res.redirect('/');
});

app.get('/loggedin', (req, res) => {
  console.log('check login', req.user);
  res.end();
});

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'public', 'index.html'));
});

app.listen(port, () => {
  console.log('Express server is up on port 5000');
});
<commit_msg>refactor server.js<commit_after>import path from 'path';
import passport from 'passport';
import express from 'express';

require('dotenv').config();

const session = require('express-session');

const GoogleStrategy = require('passport-google-oauth20').Strategy;

const port = process.env.PORT || 5000;
const app = express();
app.use(passport.initialize());
app.use(passport.session());
app.use(session({
  secret: 'keyboard cat',
  key: 'user_sid',
  resave: false,
  saveUninitialized: false,
  cookie: { expires: 600000 },
}));
app.use(express.static('public'));

passport.serializeUser((user, done) => {
  done(null, user);
});

passport.deserializeUser((obj, done) => {
  done(null, obj);
});

passport.use(new GoogleStrategy({
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: process.env.CALLBACK_URL,
},
  (accessToken, refreshToken, profile, cb) =>
    // User.findOrCreate({ googleId: profile.id }, function (err, user) {
      // process.nextTick(function () {
     cb(null, profile, accessToken)
    // });
    // return cb(null, profile);
    // });
  ,
));

app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile'] }));

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/' }),
  (req, res) => {
    console.log('userinfo', req.user);
    // Successful authentication, redirect home.
    res.redirect('/home');
  });

app.get('/logout', (req, res) => {
  req.logOut();
  res.clearCookie('user_sid');
  res.redirect('/');
});

app.get('/loggedin', (req, res) => {
  console.log('check login', req.session.user);
  res.end();
});

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'public', 'index.html'));
});

app.listen(port, () => {
  console.log('Express server is up on port 5000');
});
<|endoftext|>


<commit_before>var express = require('express')
	, _ = require('underscore')
	, feeds = require('./lib/aggregator');

var app = express();

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.enable('view cache');
app.use(app.router);
app.use(require('connect-assets')());
app.use(express.static(__dirname + '/public'));

var news_feeds = feeds();

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

app.get('/load',function(req,res){
    res.send('hello');
})

app.listen(3000);<commit_msg>dumping memory usage to log.<commit_after>var express = require('express')
	, _ = require('underscore')
	, feeds = require('./lib/aggregator')
  , util = require('util');

var app = express();

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.enable('view cache');
app.use(app.router);
app.use(require('connect-assets')());
app.use(express.static(__dirname + '/public'));

var news_feeds = feeds();

app.get('/',function(req,res){
    console.log(util.inspect(process.memoryUsage()));
	res.render('index',{feeds: news_feeds});
});

app.get('/load',function(req,res){
    res.send('hello');
})

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


<commit_before>var http = require('http'),
    express = require('express'),
    connect = require('connect'),
    routes = require("./controllers"),
    port = process.env.port || 1337,
    fs = require("fs"),
    path = require("path");

var app = express();
var router = express.Router();

app.use(router);
app.set('view engine', 'html');
app.set('layout', 'layout');
app.set('views', __dirname + "/views");
app.set('partials', {
    sidebar: "_sidebar"
});

// Load our controllers
fs.readdirSync("./controllers").forEach(function (file) {
    console.log("Processing controller:", file);

    if (file.substr(-3) == ".js") {
        route = require("./controllers/" + file);
        route.controller(app);
    }
});

//app.enable('view cache');
app.engine('html', require('hogan-express'));
app.use(express.static(path.join(__dirname + "/public")));

var server = app.listen(port, function () {
    console.log("Server started: http://localhost:" + port);
});
<commit_msg>Removed unused require<commit_after>var http = require('http'),
    express = require('express'),
    connect = require('connect'),
    port = process.env.port || 1337,
    fs = require("fs"),
    path = require("path");

var app = express();
var router = express.Router();

app.use(router);
app.set('view engine', 'html');
app.set('layout', 'layout');
app.set('views', __dirname + "/views");
app.set('partials', {
    sidebar: "_sidebar"
});

// Load our controllers
fs.readdirSync("./controllers").forEach(function (file) {
    console.log("Processing controller:", file);

    if (file.substr(-3) == ".js") {
        route = require("./controllers/" + file);
        route.controller(app);
    }
});

//app.enable('view cache');
app.engine('html', require('hogan-express'));
app.use(express.static(path.join(__dirname + "/public")));

var server = app.listen(port, function () {
    console.log("Server started: http://localhost:" + port);
});
<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var hyperstream = require('hyperstream')
var app = require('./src/app.js')
var store = require('./src/store.js')
var httpProxy = require('http-proxy')
// var proxy = httpProxy.createProxyServer({target: 'http://elmalvinense.com'})
var proxycake = httpProxy.createProxyServer({target: 'http://192.168.1.64'})
var request = require('request')
var oppressor = require('oppressor')

var ecstatic = require('ecstatic')
var st = ecstatic(path.join(__dirname, 'build'))

var http = require('http')

var server = http.createServer(function (req, res) {
  if (req.url.match('manifest.json')) return st(req,res)
  if (req.url.match('service-worker.js')) return st(req,res)
  if (req.url.match('assets')) return st(req, res)
  if (req.url.match('api')) {
    req.url = '/cake/Web-OvnionPanel-Back' + req.url
    return proxycake.web(req, res)
  }
  if (req.url.match('elmalvinense')) {
    return request('http://elmalvinense.com/elmalvinense.xml').pipe(res)
  }
  store({type: 'setUrl', payload: req.url})
  var state = store.getState()
  var hyd = JSON.stringify(state)
    var elem =  app(state)
  read('index.html').pipe(hyperstream({
      '#main': elem,
      '#state': {
        _html: "window.state =" + hyd
      }
    })).pipe(oppressor(req)).pipe(res)
})
server.listen(8000)

function read (x) {
  return fs.createReadStream(path.join(__dirname, 'build', x))
}
<commit_msg>Fix html header<commit_after>var fs = require('fs')
var path = require('path')
var hyperstream = require('hyperstream')
var app = require('./src/app.js')
var store = require('./src/store.js')
var httpProxy = require('http-proxy')
// var proxy = httpProxy.createProxyServer({target: 'http://elmalvinense.com'})
var proxycake = httpProxy.createProxyServer({target: 'http://192.168.1.64'})
var request = require('request')
var oppressor = require('oppressor')

var ecstatic = require('ecstatic')
var st = ecstatic(path.join(__dirname, 'build'))

var http = require('http')

var server = http.createServer(function (req, res) {
  if (req.url.match('manifest.json')) return st(req,res)
  if (req.url.match('service-worker.js')) return st(req,res)
  if (req.url.match('assets')) return st(req, res)
  if (req.url.match('api')) {
    req.url = '/cake/Web-OvnionPanel-Back' + req.url
    return proxycake.web(req, res)
  }
  if (req.url.match('elmalvinense')) {
    return request('http://elmalvinense.com/elmalvinense.xml').pipe(res)
  }
  res.setHeader('Content-Type', 'text/html');

  store({type: 'setUrl', payload: req.url})
  var state = store.getState()
  var hyd = JSON.stringify(state)
    var elem =  app(state)
  read('index.html').pipe(hyperstream({
      '#main': elem,
      '#state': {
        _html: "window.state =" + hyd
      }
    })).pipe(oppressor(req)).pipe(res)
})
server.listen(8000)

function read (x) {
  return fs.createReadStream(path.join(__dirname, 'build', x))
}
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var router = express.Router();
var mustacheExpress = require('mustache-express');
var humanize = require('humanizer');
var icons = require('glyphicons');
var jwt = require('jsonwebtoken');
var querystring = require('querystring');
var http = require('http');

var secret = process.env.TOKENS_KSOTD || 'shhhhh';
var phrase = process.env.PHRASE_KSOTD || 'hakunamatata';

var apiCall = function(path, method, signed, data, success, err) {
    let host = process.env.API || 'api.keyboardshortcutoftheday.com';
    let port = process.env.API_PORT || '80';
    let headers = {'X-API-Key': signed};
    let dataString = JSON.stringify(data);
    if(method === 'GET' && data) {
        path += '?' + querystring.stringify(data);
    } else {
        headers = {
            'Content-Type': 'application/json',
            'Content-Length': dataString.length,
            'X-API-Key': signed
          };
    }
    let options = {
        host,
        port,
        path,
        method,
        headers,
        timeout: 300
      };
      try {
            let req = http.request(options, function(anError, res, body){

            res.setEncoding('utf-8');
            var responseString = '';

            res.on('data', function(data){
                     responseString += data;
                 });

            res.on('end', function(){
                     if(responseString) {
                         let responseObject = JSON.parse(responseString);
                         if(responseObject.message) {
                             err(responseObject, req);
                             return;
                         }
                         success(responseObject);
                     } else {
                         err('No response', req);
                     }
                 });
            });

            req.on('error', err);
            req.write(dataString);
            req.end();
        } catch (error) {
            err('Api calls are broken', error);
        }
}

var shortcut = {
    message: 'Not yet'
}

var emptyShortcut = shortcut;

var getShortcut = function(signed, res) {

    process.on('uncaughtException', function(anErr) {
        // handle the error safely
        res.render('error', { token: signed, message: 'Unhandled error ' + annErr.message});
    })

    apiCall('/shortcuts/1', 'GET', signed, null, function (dataObject){
        shortcut = dataObject || emptyShortcut;
        res.render('index', { title: 'Keyboard shortcut of the day', dissa: icons.ticket, token: signed, 'shortcut' : JSON.stringify(shortcut), 'description': shortcut.description, stitle: shortcut.title, vendor: shortcut.vendor, product: shortcut.product, keys: shortcut.keycombo, documentation: shortcut.documentation });
    },
    function(error, req){
        res.render('error', { message: error.message, token: signed});
    }
    );
}

router.get('/', function (req, res) {
    var signed = jwt.sign({ phrase }, secret, { expiresIn: '1h'});
    getShortcut(signed, res);
})

var app = express();
app.use(express.static('public'));
app.engine('html', mustacheExpress());
app.set('views', 'views');
app.set('view engine', 'html');
app.use('/js', [express.static(__dirname + '/node_modules/jquery/dist/'),
                express.static(__dirname + '/node_modules/bootstrap/dist/js/'),
                express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/js/'),
                express.static(__dirname + '/node_modules/popper.js/dist/')]);
app.use('/css', [express.static(__dirname + '/node_modules/bootstrap/dist/css/'),
                express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/css/')]);
app.use('/webfonts', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/webfonts/'));
app.use('/sprites', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/sprites/'));
app.use('/svg', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/svg/'));
app.use('/', router);

app.listen(process.env.PORT || 8080);<commit_msg>Fixing request logic<commit_after>'use strict';

var express = require('express');
var router = express.Router();
var mustacheExpress = require('mustache-express');
var humanize = require('humanizer');
var icons = require('glyphicons');
var jwt = require('jsonwebtoken');
var querystring = require('querystring');
var http = require('http');

var secret = process.env.TOKENS_KSOTD || 'shhhhh';
var phrase = process.env.PHRASE_KSOTD || 'hakunamatata';

var apiCall = function(path, method, signed, data, success, err) {
    let host = process.env.API || 'api.keyboardshortcutoftheday.com';
    let port = process.env.API_PORT || '80';
    let headers = {'X-API-Key': signed};
    let dataString = JSON.stringify(data);
    if(method === 'GET' && data) {
        path += '?' + querystring.stringify(data);
    } else {
        headers = {
            'Content-Type': 'application/json',
            'Content-Length': dataString.length,
            'X-API-Key': signed
          };
    }
    let options = {
        host,
        port,
        path,
        method,
        headers,
        timeout: 300
      };
      try {
            let req = http.request(options, function(res){

            res.setEncoding('utf-8');
            var responseString = '';

            res.on('data', function(data){
                     responseString += data;
                 });

            res.on('end', function(){
                     if(responseString) {
                         let responseObject = JSON.parse(responseString);
                         if(responseObject.message) {
                             err(responseObject, req);
                             return;
                         }
                         success(responseObject);
                     } else {
                         err('No response', req);
                     }
                 });
            });

            req.on('error', err);
            req.write(dataString);
            req.end();
        } catch (error) {
            err('Api calls are broken', error);
        }
}

var shortcut = {
    message: 'Not yet'
}

var emptyShortcut = shortcut;

var getShortcut = function(signed, res) {

    process.on('uncaughtException', function(anErr) {
        // handle the error safely
        res.render('error', { token: signed, message: 'Unhandled error ' + annErr.message});
    })

    apiCall('/shortcuts/1', 'GET', signed, null, function (dataObject){
        shortcut = dataObject || emptyShortcut;
        res.render('index', { title: 'Keyboard shortcut of the day', dissa: icons.ticket, token: signed, 'shortcut' : JSON.stringify(shortcut), 'description': shortcut.description, stitle: shortcut.title, vendor: shortcut.vendor, product: shortcut.product, keys: shortcut.keycombo, documentation: shortcut.documentation });
    },
    function(error, req){
        res.render('error', { message: error.message, token: signed});
    }
    );
}

router.get('/', function (req, res) {
    var signed = jwt.sign({ phrase }, secret, { expiresIn: '1h'});
    getShortcut(signed, res);
})

var app = express();
app.use(express.static('public'));
app.engine('html', mustacheExpress());
app.set('views', 'views');
app.set('view engine', 'html');
app.use('/js', [express.static(__dirname + '/node_modules/jquery/dist/'),
                express.static(__dirname + '/node_modules/bootstrap/dist/js/'),
                express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/js/'),
                express.static(__dirname + '/node_modules/popper.js/dist/')]);
app.use('/css', [express.static(__dirname + '/node_modules/bootstrap/dist/css/'),
                express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/css/')]);
app.use('/webfonts', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/webfonts/'));
app.use('/sprites', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/sprites/'));
app.use('/svg', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/svg/'));
app.use('/', router);

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


<commit_before>'use strict';

/*
 * Express Dependencies
 */
var express  = require('express');
var app      = express();
var database = require('./lib/database/sequelize');
var bootstrap = require('./lib/bootstrap');
var port     = process.env.PORT || 9000;

/*
 * App methods and libraries
 */
app.root = __dirname;
app.config = require('./config.js');
app.api = require('./lib/api');
app.classes = require('./lib/classes');
app.db = database.db;
app.db.raw = database.raw;

// propagate app instance throughout app methods
app.api.init(app);

database.init(app).then(function () {
  console.log('database initialized!');
}, function (databaseErr) {
  console.log('database initialization failed due to:', databaseErr);
  process.exit(2);
}).then(function () {
  bootstrap(app);

  // "app.router" positions our routes
  // above the middleware defined below,
  // this means that Express will attempt
  // to match & call routes _before_ continuing
  // on, at which point we assume it's a 404 because
  // no route has handled the request.
  app.use(app.router);

  // host dev files if in dev mode
  if (/^development|test$/.test(app.get('env'))) {
    app.use(express.static('.tmp'));
    app.use(express.static('app'));
  } else if (app.get('env') === 'production') {
    app.use(express.static('dist/app'));
  }

  // Since this is the last non-error-handling
  // middleware use()d, we assume 404, as nothing else
  // responded.

  // $ curl http://localhost:3000/notfound
  // $ curl http://localhost:3000/notfound -H "Accept: application/json"
  // $ curl http://localhost:3000/notfound -H "Accept: text/plain"

  app.use(function(req, res, next) {
    res.status(404);

    // respond with html page
    if (req.accepts('html')) {
      res.render('404', { url: req.url });
      return;
    }

    // respond with json
    if (req.accepts('json')) {
      res.send({ error: 'Not found' });
      return;
    }

    // default to plain-text. send()
    res.type('txt').send('Not found');
  });

  // error-handling middleware, take the same form
  // as regular middleware, however they require an
  // arity of 4, aka the signature (err, req, res, next).
  // when connect has an error, it will invoke ONLY error-handling
  // middleware.

  // If we were to next() here any remaining non-error-handling
  // middleware would then be executed, or if we next(err) to
  // continue passing the error, only error-handling middleware
  // would remain being executed, however here
  // we simply respond with an error page.

  app.use(function(err, req, res, next) {
    // we may use properties of the error object
    // here and next(err) appropriately, or if
    // we possibly recovered from the error, simply next().
    res.status(err.status || (err.status = 500));

    console.error('Server error catch-all says: ', err);

    // prevent users from seeing specific error messages in production
    if (app.get('env') !== 'development') {
      var newErr = new Error('Something went wrong. Sorry!');
      newErr.status = err.status;
      err = newErr;
    }

    // respond depending on highest-quality accepted format
    res.format({
      json: function () {
        res.send({
          data: err,
          message: err.message
        });
      },

      html: function () {
        res.render('errors', {
          data: err,
          message: err.message
        });
      },

      text: function () {
        res.send('Error ' + err.status);
      }
    });
  });

  /*
  * Routes
  */
  function renderApp (req, res, next) {
    app.db.groups.browse().then(function (groups) {
      var preload = { groups: groups };

      res.render('app', {
        preloadGroups: JSON.stringify(preload)
      });
    });
  }

  app.get('/', renderApp);

  app.get('/api/v1/groups', app.api.v1.groups.browse);
  app.get('/api/v1/groups/:group_id', app.api.v1.groups.read);

  app.get('/api/v1/groups/:group_id/items', app.api.v1.items.get.itemsByGroup);
  app.get('/api/v1/items', app.api.v1.items.get.all);
  app.get('/api/v1/items/:item_id', app.api.v1.items.get.itemById);

  app.get('/groups', renderApp);
  app.get('/groups/:group_id', renderApp);
  app.get('/groups/:group_id/edit', renderApp);
  app.get('/groups/:group_id/items', renderApp);
  app.get('/groups/:group_id/items/:item_id', renderApp);
  app.get('/groups/:group_id/items/:item_id/edit', renderApp);

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

  app.get('/index', function (req, res) {
    res.send(200, require('fs').readFileSync('index.html', {encoding: 'utf8'}));
  });

  app.post('/normal', function (req, res) {
    console.log('picture was', req.body, req.files);
    res.send(200);
  });

  // app.get('/api/v1/people', app.api.v1.people.getAll);
  // app.get('/api/v1/peopleError', app.api.v1.people.getError);

  // app.put('/api/v1/people/:id', function (req, res) {
  //   // the database library would normally save
  //   // the record and return the updated record.
  //   req.body.person.id = req.params.id;
  //   res.send(req.body);
  // });

  /*
  * Status Code pages
  */
  app.get('/404', function(req, res, next){
    // trigger a 404 since no other middleware
    // will match /404 after this one, and we're not
    // responding here
    next();
  });

  app.get('/403', function(req, res, next){
    // trigger a 403 error
    var err = new Error('not allowed!');
    err.status = 403;
    next(err);
  });

  app.get('/500', function(req, res, next){
    // trigger a generic (500) error
    next(new Error('keyboard cat!'));
  });

  app.listen(port);
  console.log('Express started on port ' + port);
}).catch(function (err) {
  console.error('App encountered an error:', err);
  process.exit(1);
});

<commit_msg>Remove some remnants from another project<commit_after>'use strict';

/*
 * Express Dependencies
 */
var express  = require('express');
var app      = express();
var database = require('./lib/database/sequelize');
var bootstrap = require('./lib/bootstrap');
var port     = process.env.PORT || 9000;

/*
 * App methods and libraries
 */
app.root = __dirname;
app.config = require('./config.js');
app.api = require('./lib/api');
app.classes = require('./lib/classes');
app.db = database.db;
app.db.raw = database.raw;

// propagate app instance throughout app methods
app.api.init(app);

database.init(app).then(function () {
  console.log('database initialized!');
}, function (databaseErr) {
  console.log('database initialization failed due to:', databaseErr);
  process.exit(2);
}).then(function () {
  bootstrap(app);

  // "app.router" positions our routes
  // above the middleware defined below,
  // this means that Express will attempt
  // to match & call routes _before_ continuing
  // on, at which point we assume it's a 404 because
  // no route has handled the request.
  app.use(app.router);

  // host dev files if in dev mode
  if (/^development|test$/.test(app.get('env'))) {
    app.use(express.static('.tmp'));
    app.use(express.static('app'));
  } else if (app.get('env') === 'production') {
    app.use(express.static('dist/app'));
  }

  // Since this is the last non-error-handling
  // middleware use()d, we assume 404, as nothing else
  // responded.

  // $ curl http://localhost:3000/notfound
  // $ curl http://localhost:3000/notfound -H "Accept: application/json"
  // $ curl http://localhost:3000/notfound -H "Accept: text/plain"

  app.use(function(req, res, next) {
    res.status(404);

    // respond with html page
    if (req.accepts('html')) {
      res.render('404', { url: req.url });
      return;
    }

    // respond with json
    if (req.accepts('json')) {
      res.send({ error: 'Not found' });
      return;
    }

    // default to plain-text. send()
    res.type('txt').send('Not found');
  });

  // error-handling middleware, take the same form
  // as regular middleware, however they require an
  // arity of 4, aka the signature (err, req, res, next).
  // when connect has an error, it will invoke ONLY error-handling
  // middleware.

  // If we were to next() here any remaining non-error-handling
  // middleware would then be executed, or if we next(err) to
  // continue passing the error, only error-handling middleware
  // would remain being executed, however here
  // we simply respond with an error page.

  app.use(function(err, req, res, next) {
    // we may use properties of the error object
    // here and next(err) appropriately, or if
    // we possibly recovered from the error, simply next().
    res.status(err.status || (err.status = 500));

    console.error('Server error catch-all says: ', err);

    // prevent users from seeing specific error messages in production
    if (app.get('env') !== 'development') {
      var newErr = new Error('Something went wrong. Sorry!');
      newErr.status = err.status;
      err = newErr;
    }

    // respond depending on highest-quality accepted format
    res.format({
      json: function () {
        res.send({
          data: err,
          message: err.message
        });
      },

      html: function () {
        res.render('errors', {
          data: err,
          message: err.message
        });
      },

      text: function () {
        res.send('Error ' + err.status);
      }
    });
  });

  /*
  * Routes
  */
  function renderApp (req, res, next) {
    app.db.groups.browse().then(function (groups) {
      var preload = { groups: groups };

      res.render('app', {
        preloadGroups: JSON.stringify(preload)
      });
    });
  }

  app.get('/', renderApp);

  app.get('/api/v1/groups', app.api.v1.groups.browse);
  app.get('/api/v1/groups/:group_id', app.api.v1.groups.read);

  app.get('/api/v1/groups/:group_id/items', app.api.v1.items.get.itemsByGroup);
  app.get('/api/v1/items', app.api.v1.items.get.all);
  app.get('/api/v1/items/:item_id', app.api.v1.items.get.itemById);

  app.get('/groups', renderApp);
  app.get('/groups/:group_id', renderApp);
  app.get('/groups/:group_id/edit', renderApp);
  app.get('/groups/:group_id/items', renderApp);
  app.get('/groups/:group_id/items/:item_id', renderApp);
  app.get('/groups/:group_id/items/:item_id/edit', renderApp);

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

  app.get('/index', function (req, res) {
    res.send(200, require('fs').readFileSync('index.html', {encoding: 'utf8'}));
  });

  app.post('/normal', function (req, res) {
    console.log('picture was', req.body, req.files);
    res.send(200);
  });

  /*
  * Status Code pages
  */
  app.get('/404', function(req, res, next){
    // trigger a 404 since no other middleware
    // will match /404 after this one, and we're not
    // responding here
    next();
  });

  app.get('/403', function(req, res, next){
    // trigger a 403 error
    var err = new Error('not allowed!');
    err.status = 403;
    next(err);
  });

  app.get('/500', function(req, res, next){
    // trigger a generic (500) error
    next(new Error('keyboard cat!'));
  });

  app.listen(port);
  console.log('Express started on port ' + port);
}).catch(function (err) {
  console.error('App encountered an error:', err);
  process.exit(1);
});

<|endoftext|>


<commit_before>var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var bodyParser = require('body-parser');
var app = express();
var currentDB;
var mongoOp = require("./model/mongo");
var router = express.Router();
var config = require('./config');
var twilio = require('twilio');
var admin = require('./admin');
var cookieParser = require('cookie-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));

var app = express();
app.use(cookieParser());

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

router.get("/",function(req,res){
  res.json({"error" : false,"message" : "available"});
});

router.route("/twilio")
.get(function(req,res){
  console.log('----Twilio From: ' + req.query['From'] + ' Message ' + req.query['Body']);
  var bodyText = req.query['Body'].toLowerCase();
  var fromPhoneNumber = req.query['From'];
  var familyId = 0;

  var cachedListName;
  if (req.cookies !== undefined && req.cookies.listName !== undefined) {
    cachedListName = req.cookies.listName;
    if (bodyText.startsWith("add ") || bodyText.startsWith("remove ")) {
      bodyText = '#' + cachedListName + ' ' + bodyText;
      console.log('add command changed to ' + bodyText);
    }
  }

  //Check FamilyId
  mongoOp.FamilyMembers.findOne({'phoneNumber': fromPhoneNumber }, 'familyId', function (err, familyMember) {
    if (familyMember == null) {
      sendSMSResponse(fromPhoneNumber, 0, bodyText, "Sorry, don't see you as a member of a family.", res);
    } else {
      familyId = familyMember.familyId;
      log(fromPhoneNumber, familyId, bodyText, "request", "");

      //MAIN LOGIC
      if (bodyText === "get lists" || bodyText === "get") {
        response = true;
        mongoOp.Lists.find({'familyId':familyId}, 'listKey', function(err, lists) {
          if(err){
            logError(fromPhoneNumber, familyId, bodyText, err);
          } else {
            var concatText = "";

            lists.forEach(function(list){
              concatText = concatText.concat('\n#' + list.listKey);
            });
            sendSMSResponse(fromPhoneNumber, familyId, bodyText, concatText, res);
          }
        });

      // } else if (bodyText === "fix")  {
      //   mongoOp.ListItems.find({},function(err,listItems) {
      //     listItems.forEach(function(listItem){
      //       listItem.familyId = 1;
      //       listItem.save(function(err){
      //         if(err) {
      //           console.log('---->>>> fix error');
      //         } else {
      //           console.log('---->>>> fix SUCCESS!!!!');
      //         }
      //       });
      //     });
      //   });

      // Basic welcome message
      } else if (bodyText.startsWith("** welcome ")) {
        console.log('*** Send welcome');
        response = true;
        var welcomeSendUserId = bodyText.substr(12);
        mongoOp.FamilyMembers.findOne({'id': welcomeSendUserId}, 'phoneNumber', function(err, familyMember) {
        console.log('send to ' + welcomeSendUserId + 'phone number is ' + familyMember.phoneNumber);
          admin.sendSms(familyMember.phoneNumber,'Welcome to FLOCK!\nYou now have the power to crowdsource your family lists. \nLearn more - text the word “flock” to this number to see a list of available commands.\nHave fun!\n❤FLOCK');
        });

      // Get list items
      } else if (bodyText.startsWith("get #")) {
        console.log('*** get list!!!!');
        response = true;
        var listName = bodyText.substr(5);

        mongoOp.Lists.findOne({'listKey': listName, 'familyId': familyId}, 'listKey', function(err, list) {
          if (list == null) {
            sendSMSResponse(fromPhoneNumber, familyId, bodyText, '#' + listName + ' does not exist.', res);
          } else {
            mongoOp.ListItems.find({'listKey':listName, 'familyId': familyId}, function(err, listItems){
              if(err){
                logError(fromPhoneNumber, familyId, bodyText, err);
              } else {
                var concatText = "";
                var itemNumber = 0;
                listItems.forEach(function(listItem){
                  itemNumber++;
                  concatText = concatText.concat('\n• ' + listItem.listItemName);
                });
                if (itemNumber == 0) {
                  concatText = concatText.concat('No items in #' + listName + '.');
                }
                cacheListName(listName,res);
                sendSMSResponse(fromPhoneNumber, familyId, bodyText, '\n#'+ listName + ':' + concatText, res);
             }
            });
          }
        });

      } else if (bodyText.startsWith('#')) {

        var listName = getFirstWord(bodyText).substr(1);
        mongoOp.Lists.findOne({'listKey': listName, 'familyId': familyId}, 'listKey', function(err, list) {

          if (list == null) {
            sendSMSResponse(fromPhoneNumber, familyId, bodyText, '#' + listName + ' does not exist.', res);
          } else {
            var addVerbPhrase = '#' + listName + ' add ';
            var removeVerbPhrase = '#' + listName + ' remove ';

            //Add item
            if (bodyText.startsWith(addVerbPhrase)) {
              var listItemName = bodyText.substr(addVerbPhrase.length);

              var newItem = new mongoOp.ListItems({
                "listKey" : listName,
                "listItemName" : listItemName,
                "familyId" : familyId
              });
              newItem.save(function (err, data) {
                if (err) logError(fromPhoneNumber, familyId, bodyText, err);
                else {
                  console.log('----saved ', data );
                  cacheListName(listName,res);
                  sendSMSResponse(fromPhoneNumber, familyId, bodyText, 'Got it! ❤FLOCK', res);
                }
              });

            //Remove list item
            } else if (bodyText.startsWith(removeVerbPhrase)) {
              var listItemName = bodyText.substr(removeVerbPhrase.length);

              mongoOp.ListItems.remove({"listKey" : listName,"listItemName" : listItemName, 'familyId': familyId}, function(err, removeResult) {
                if (err) {
                  logError(fromPhoneNumber, familyId, bodyText, err);
                  return;
                }
                console.log('----removed ' + listItemName + ' ' + removeResult.result.n);
                if (removeResult.result.n === 0) {
                  sendSMSResponse(fromPhoneNumber, familyId, bodyText, listItemName + " doesn't exist in #" + listName + ".", res);
                } else {
                  sendSMSResponse(fromPhoneNumber, familyId, bodyText, 'Got it! ❤FLOCK', res);
                }
              });
            }

          }
        });

      // Create list.
      } else if (bodyText.startsWith('create #')) {
        var newListName = bodyText.substr(8)
        mongoOp.Lists.findOne({'listKey': newListName, 'familyId': familyId}, 'listKey', function(err, list) {

          if (list != null) {
            sendSMSResponse(fromPhoneNumber, familyId, bodyText, 'List already exists!', res);
          } else {

            if (newListName.includes(' ')) {
              sendSMSResponse(fromPhoneNumber, familyId, bodyText, "Sorry, but please don't include spaces in list names.", res);
              return;
            }

            var newList = new mongoOp.Lists({
              "listKey" : newListName,
              "listDescription" : "",
              "familyId" : familyId
            });
            newList.save(function (err, data) {
              if (err) logError(fromPhoneNumber, familyId, bodyText, err);
              else {
                console.log('----saved ', data );
                cacheListName(newListName,res);
                sendSMSResponse(fromPhoneNumber, familyId, bodyText, 'Got it! ❤FLOCK', res);
              }
            });
          }
        });

      // Clear list.
      } else if (bodyText.startsWith('clear #')) {
        var listName = bodyText.substr(7)
        mongoOp.Lists.findOne({'listKey': listName, 'familyId': familyId}, 'listKey', function(err, list) {

          if (list == null) {
            sendSMSResponse(fromPhoneNumber, familyId, bodyText, '#' + listName + ' does not exist.', res);
          } else {

            mongoOp.ListItems.remove({"listKey" : list.listKey, 'familyId': familyId}, function(err, removeResult) {
              if (err) {
                logError(fromPhoneNumber, familyId, bodyText, err);
                return;
              }
              console.log('----cleared ' + list.listKey + ' ' + removeResult.result.n);
              if (removeResult.result.n === 0) {
                sendSMSResponse(fromPhoneNumber, familyId, bodyText, "#" + list.listKey + " already empty.", res);
              } else {
                sendSMSResponse(fromPhoneNumber, familyId, bodyText, 'Got it! ❤FLOCK', res);
              }
            });

          }

        });

      // delete list.
      } else if (bodyText.startsWith('delete #')) {
        var listName = bodyText.substr(8)

        mongoOp.Lists.findOne({'listKey': listName, 'familyId': familyId}, 'listKey', function(err, list) {
          if (list == null) {
            sendSMSResponse(fromPhoneNumber, familyId, bodyText, '#' + listName + ' does not exist.', res);
          } else {

            mongoOp.Lists.remove({"listKey" : list.listKey, 'familyId': familyId}, function(err, removeResult) {
              if (err) {
                logError(fromPhoneNumber, familyId, bodyText, err);
                return;
              }
              console.log('----deleted ' + list.listKey + ' ' + removeResult.result.n);
              sendSMSResponse(fromPhoneNumber, familyId, bodyText, 'Got it! ❤FLOCK', res);
            });

          }

        });

      // help
      } else if (bodyText === 'flock') {
        sendSMSResponse(fromPhoneNumber, familyId, bodyText, "Welcome to ❤FLOCK\nThe Family Operating System\n\nUse the following commands:\n• get -OR- get lists\n• create #list\n• get #list\n• #list add item -OR - just 'add item' if already got list\n• #list remove item -OR- just 'remove item' if already got list\n• clear #list\n• delete #list", res);

      // catch all
      } else {
        sendSMSResponse(fromPhoneNumber, familyId, bodyText, "Sorry, don't understand.  Type 'flock' for more info.", res);
      }

    }
  });
});

app.use('/',router);

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

function sendSMSResponse(phoneNumber, familyId, inMessage, outMessage, response) {
  var twilioResponse = new twilio.TwimlResponse();
  twilioResponse.message(outMessage);
  response.send(twilioResponse.toString());
  log(phoneNumber, familyId, inMessage, "response", outMessage);
};

function cacheListName(listName,response) {
  response.cookie('listName', listName, { maxAge: 1000 * 60 * 60 });
};

function logError(phoneNumber, familyId, message, err) {
  log(phoneNumber, familyId, inMessage, "error", err);
  console.log(err);
}

function log(phoneNumber, familyId, message, type, response) {
  var newLog = new mongoOp.Logs({
    "phoneNumber" : phoneNumber,
    "familyId" : familyId,
    "message" : message,
    "dateTime" : Date(),
    "type" : type,
    "response" : response
  });
  newLog.save(function (err, data) {
    if (err) console.log(err);
  });
};

function getFirstWord(str) {
  if (str.indexOf(' ') === -1)
    return str;
  else
    return str.substr(0, str.indexOf(' '));
};<commit_msg>welcome<commit_after>var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var bodyParser = require('body-parser');
var app = express();
var currentDB;
var mongoOp = require("./model/mongo");
var router = express.Router();
var config = require('./config');
var twilio = require('twilio');
var admin = require('./admin');
var cookieParser = require('cookie-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));

var app = express();
app.use(cookieParser());

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

router.get("/",function(req,res){
  res.json({"error" : false,"message" : "available"});
});

router.route("/twilio")
.get(function(req,res){
  console.log('----Twilio From: ' + req.query['From'] + ' Message ' + req.query['Body']);
  var bodyText = req.query['Body'].toLowerCase();
  var fromPhoneNumber = req.query['From'];
  var familyId = 0;

  var cachedListName;
  if (req.cookies !== undefined && req.cookies.listName !== undefined) {
    cachedListName = req.cookies.listName;
    if (bodyText.startsWith("add ") || bodyText.startsWith("remove ")) {
      bodyText = '#' + cachedListName + ' ' + bodyText;
      console.log('add command changed to ' + bodyText);
    }
  }

  //Check FamilyId
  mongoOp.FamilyMembers.findOne({'phoneNumber': fromPhoneNumber }, 'familyId', function (err, familyMember) {
    if (familyMember == null) {
      sendSMSResponse(fromPhoneNumber, 0, bodyText, "Sorry, don't see you as a member of a family.", res);
    } else {
      familyId = familyMember.familyId;
      log(fromPhoneNumber, familyId, bodyText, "request", "");

      //MAIN LOGIC
      if (bodyText === "get lists" || bodyText === "get") {
        response = true;
        mongoOp.Lists.find({'familyId':familyId}, 'listKey', function(err, lists) {
          if(err){
            logError(fromPhoneNumber, familyId, bodyText, err);
          } else {
            var concatText = "";

            lists.forEach(function(list){
              concatText = concatText.concat('\n#' + list.listKey);
            });
            sendSMSResponse(fromPhoneNumber, familyId, bodyText, concatText, res);
          }
        });

      // } else if (bodyText === "fix")  {
      //   mongoOp.ListItems.find({},function(err,listItems) {
      //     listItems.forEach(function(listItem){
      //       listItem.familyId = 1;
      //       listItem.save(function(err){
      //         if(err) {
      //           console.log('---->>>> fix error');
      //         } else {
      //           console.log('---->>>> fix SUCCESS!!!!');
      //         }
      //       });
      //     });
      //   });

      // Basic welcome message
      } else if (bodyText.startsWith("** welcome ")) {
        console.log('*** Send welcome');
        response = true;
        var welcomeSendUserId = bodyText.substr(11);
        mongoOp.FamilyMembers.findOne({'id': welcomeSendUserId}, 'phoneNumber', function(err, familyMember) {
        console.log('send to ' + welcomeSendUserId + 'phone number is ' + familyMember.phoneNumber);
          admin.sendSms(familyMember.phoneNumber,'Welcome to FLOCK!\nYou now have the power to crowdsource your family lists. \nLearn more - text the word “flock” to this number to see a list of available commands.\nHave fun!\n❤FLOCK');
        });

      // Get list items
      } else if (bodyText.startsWith("get #")) {
        console.log('*** get list!!!!');
        response = true;
        var listName = bodyText.substr(5);

        mongoOp.Lists.findOne({'listKey': listName, 'familyId': familyId}, 'listKey', function(err, list) {
          if (list == null) {
            sendSMSResponse(fromPhoneNumber, familyId, bodyText, '#' + listName + ' does not exist.', res);
          } else {
            mongoOp.ListItems.find({'listKey':listName, 'familyId': familyId}, function(err, listItems){
              if(err){
                logError(fromPhoneNumber, familyId, bodyText, err);
              } else {
                var concatText = "";
                var itemNumber = 0;
                listItems.forEach(function(listItem){
                  itemNumber++;
                  concatText = concatText.concat('\n• ' + listItem.listItemName);
                });
                if (itemNumber == 0) {
                  concatText = concatText.concat('No items in #' + listName + '.');
                }
                cacheListName(listName,res);
                sendSMSResponse(fromPhoneNumber, familyId, bodyText, '\n#'+ listName + ':' + concatText, res);
             }
            });
          }
        });

      } else if (bodyText.startsWith('#')) {

        var listName = getFirstWord(bodyText).substr(1);
        mongoOp.Lists.findOne({'listKey': listName, 'familyId': familyId}, 'listKey', function(err, list) {

          if (list == null) {
            sendSMSResponse(fromPhoneNumber, familyId, bodyText, '#' + listName + ' does not exist.', res);
          } else {
            var addVerbPhrase = '#' + listName + ' add ';
            var removeVerbPhrase = '#' + listName + ' remove ';

            //Add item
            if (bodyText.startsWith(addVerbPhrase)) {
              var listItemName = bodyText.substr(addVerbPhrase.length);

              var newItem = new mongoOp.ListItems({
                "listKey" : listName,
                "listItemName" : listItemName,
                "familyId" : familyId
              });
              newItem.save(function (err, data) {
                if (err) logError(fromPhoneNumber, familyId, bodyText, err);
                else {
                  console.log('----saved ', data );
                  cacheListName(listName,res);
                  sendSMSResponse(fromPhoneNumber, familyId, bodyText, 'Got it! ❤FLOCK', res);
                }
              });

            //Remove list item
            } else if (bodyText.startsWith(removeVerbPhrase)) {
              var listItemName = bodyText.substr(removeVerbPhrase.length);

              mongoOp.ListItems.remove({"listKey" : listName,"listItemName" : listItemName, 'familyId': familyId}, function(err, removeResult) {
                if (err) {
                  logError(fromPhoneNumber, familyId, bodyText, err);
                  return;
                }
                console.log('----removed ' + listItemName + ' ' + removeResult.result.n);
                if (removeResult.result.n === 0) {
                  sendSMSResponse(fromPhoneNumber, familyId, bodyText, listItemName + " doesn't exist in #" + listName + ".", res);
                } else {
                  sendSMSResponse(fromPhoneNumber, familyId, bodyText, 'Got it! ❤FLOCK', res);
                }
              });
            }

          }
        });

      // Create list.
      } else if (bodyText.startsWith('create #')) {
        var newListName = bodyText.substr(8)
        mongoOp.Lists.findOne({'listKey': newListName, 'familyId': familyId}, 'listKey', function(err, list) {

          if (list != null) {
            sendSMSResponse(fromPhoneNumber, familyId, bodyText, 'List already exists!', res);
          } else {

            if (newListName.includes(' ')) {
              sendSMSResponse(fromPhoneNumber, familyId, bodyText, "Sorry, but please don't include spaces in list names.", res);
              return;
            }

            var newList = new mongoOp.Lists({
              "listKey" : newListName,
              "listDescription" : "",
              "familyId" : familyId
            });
            newList.save(function (err, data) {
              if (err) logError(fromPhoneNumber, familyId, bodyText, err);
              else {
                console.log('----saved ', data );
                cacheListName(newListName,res);
                sendSMSResponse(fromPhoneNumber, familyId, bodyText, 'Got it! ❤FLOCK', res);
              }
            });
          }
        });

      // Clear list.
      } else if (bodyText.startsWith('clear #')) {
        var listName = bodyText.substr(7)
        mongoOp.Lists.findOne({'listKey': listName, 'familyId': familyId}, 'listKey', function(err, list) {

          if (list == null) {
            sendSMSResponse(fromPhoneNumber, familyId, bodyText, '#' + listName + ' does not exist.', res);
          } else {

            mongoOp.ListItems.remove({"listKey" : list.listKey, 'familyId': familyId}, function(err, removeResult) {
              if (err) {
                logError(fromPhoneNumber, familyId, bodyText, err);
                return;
              }
              console.log('----cleared ' + list.listKey + ' ' + removeResult.result.n);
              if (removeResult.result.n === 0) {
                sendSMSResponse(fromPhoneNumber, familyId, bodyText, "#" + list.listKey + " already empty.", res);
              } else {
                sendSMSResponse(fromPhoneNumber, familyId, bodyText, 'Got it! ❤FLOCK', res);
              }
            });

          }

        });

      // delete list.
      } else if (bodyText.startsWith('delete #')) {
        var listName = bodyText.substr(8)

        mongoOp.Lists.findOne({'listKey': listName, 'familyId': familyId}, 'listKey', function(err, list) {
          if (list == null) {
            sendSMSResponse(fromPhoneNumber, familyId, bodyText, '#' + listName + ' does not exist.', res);
          } else {

            mongoOp.Lists.remove({"listKey" : list.listKey, 'familyId': familyId}, function(err, removeResult) {
              if (err) {
                logError(fromPhoneNumber, familyId, bodyText, err);
                return;
              }
              console.log('----deleted ' + list.listKey + ' ' + removeResult.result.n);
              sendSMSResponse(fromPhoneNumber, familyId, bodyText, 'Got it! ❤FLOCK', res);
            });

          }

        });

      // help
      } else if (bodyText === 'flock') {
        sendSMSResponse(fromPhoneNumber, familyId, bodyText, "Welcome to ❤FLOCK\nThe Family Operating System\n\nUse the following commands:\n• get -OR- get lists\n• create #list\n• get #list\n• #list add item -OR - just 'add item' if already got list\n• #list remove item -OR- just 'remove item' if already got list\n• clear #list\n• delete #list", res);

      // catch all
      } else {
        sendSMSResponse(fromPhoneNumber, familyId, bodyText, "Sorry, don't understand.  Type 'flock' for more info.", res);
      }

    }
  });
});

app.use('/',router);

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

function sendSMSResponse(phoneNumber, familyId, inMessage, outMessage, response) {
  var twilioResponse = new twilio.TwimlResponse();
  twilioResponse.message(outMessage);
  response.send(twilioResponse.toString());
  log(phoneNumber, familyId, inMessage, "response", outMessage);
};

function cacheListName(listName,response) {
  response.cookie('listName', listName, { maxAge: 1000 * 60 * 60 });
};

function logError(phoneNumber, familyId, message, err) {
  log(phoneNumber, familyId, inMessage, "error", err);
  console.log(err);
}

function log(phoneNumber, familyId, message, type, response) {
  var newLog = new mongoOp.Logs({
    "phoneNumber" : phoneNumber,
    "familyId" : familyId,
    "message" : message,
    "dateTime" : Date(),
    "type" : type,
    "response" : response
  });
  newLog.save(function (err, data) {
    if (err) console.log(err);
  });
};

function getFirstWord(str) {
  if (str.indexOf(' ') === -1)
    return str;
  else
    return str.substr(0, str.indexOf(' '));
};<|endoftext|>