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

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

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

/**
 * Controllers (route handlers).
 */
const homeController = require("./controllers/home");
const userController = require("./controllers/user");
const apiController = require("./controllers/api");
const contactController = require("./controllers/contact");
const wordController = require("./controllers/word");
const quizController = require("./controllers/quiz");
const removeBestWord = require("./controllers/removebestword");
const quizAnalysis = require("./controllers/quizAnalysis");
const reportController = require("./controllers/report");
const comingSoon = require("./controllers/comingSoon");
const profilesOverview = require("./controllers/profilesOverview");

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

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

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

/**
 * Populate the Mongo Database with initial data
 * TODO: Make this dependant on the dev environment
 */
const db = require("./util/db");
console.log("Pre populate the database");
db();
console.log("Done pre-populating the database");

/**
 * Express configuration.
 */
app.set("port", process.env.PORT || 3000);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(expressStatusMonitor());
app.use(compression());
app.use(
  sass({
    src: path.join(__dirname, "public"),
    dest: path.join(__dirname, "public")
  })
);
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(
  session({
    resave: true,
    saveUninitialized: true,
    secret: process.env.SESSION_SECRET,
    store: new MongoStore({
      url: process.env.MONGODB_URI || process.env.MONGOLAB_URI,
      autoReconnect: true,
      clear_interval: 3600
    })
  })
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
  next();
  // if (req.path === '/api/upload') {
  //   next();
  // } else {
  //   lusca.csrf()(req, res, next);
  // }
});
app.use(lusca.xframe("SAMEORIGIN"));
app.use(lusca.xssProtection(true));
app.use((req, res, next) => {
  res.locals.user = req.user;
  next();
});
app.use((req, res, next) => {
  // After successful login, redirect back to the intended page
  if (
    !req.user &&
    req.path !== "/login" &&
    req.path !== "/signup" &&
    !req.path.match(/^\/auth/) &&
    !req.path.match(/\./)
  ) {
    req.session.returnTo = req.path;
  } else if (req.user && req.path === "/account") {
    req.session.returnTo = req.path;
  }
  next();
});
app.use(
  express.static(path.join(__dirname, "public"), { maxAge: 31557600000 })
);

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

/**
 * API examples routes.
 */
app.get("/api", apiController.getApi);
app.get("/api/lastfm", apiController.getLastfm);
app.get("/api/nyt", apiController.getNewYorkTimes);
app.get("/api/aviary", apiController.getAviary);
app.get(
  "/api/steam",
  passportConfig.isAuthenticated,
  passportConfig.isAuthorized,
  apiController.getSteam
);
app.get("/api/stripe", apiController.getStripe);
app.post("/api/stripe", apiController.postStripe);
app.get("/api/scraping", apiController.getScraping);
//app.get("/api/twilio", apiController.getTwilio);
//app.post("/api/twilio", apiController.postTwilio);
//app.get("/api/clockwork", apiController.getClockwork);
//app.post("/api/clockwork", apiController.postClockwork);
//app.get(
//   "/api/foursquare",
//   passportConfig.isAuthenticated,
//   passportConfig.isAuthorized,
//   apiController.getFoursquare
// );
// app.get(
//   "/api/tumblr",
//   passportConfig.isAuthenticated,
//   passportConfig.isAuthorized,
//   apiController.getTumblr
// );
app.get(
  "/api/facebook",
  passportConfig.isAuthenticated,
  passportConfig.isAuthorized,
  apiController.getFacebook
);
app.get(
  "/api/github",
  passportConfig.isAuthenticated,
  passportConfig.isAuthorized,
  apiController.getGithub
);
app.get(
  "/api/twitter",
  passportConfig.isAuthenticated,
  passportConfig.isAuthorized,
  apiController.getTwitter
);
app.post(
  "/api/twitter",
  passportConfig.isAuthenticated,
  passportConfig.isAuthorized,
  apiController.postTwitter
);
// app.get(
//   "/api/linkedin",
//   passportConfig.isAuthenticated,
//   passportConfig.isAuthorized,
//   apiController.getLinkedin
// );
// app.get(
//   "/api/instagram",
//   passportConfig.isAuthenticated,
//   passportConfig.isAuthorized,
//   apiController.getInstagram
// );
app.get("/api/paypal", apiController.getPayPal);
app.get("/api/paypal/success", apiController.getPayPalSuccess);
app.get("/api/paypal/cancel", apiController.getPayPalCancel);
app.get("/api/lob", apiController.getLob);
app.get("/api/upload", apiController.getFileUpload);
app.post("/api/upload", upload.single("myFile"), apiController.postFileUpload);
// app.get(
//   "/api/pinterest",
//   passportConfig.isAuthenticated,
//   passportConfig.isAuthorized,
//   apiController.getPinterest
// );
// app.post(
//   "/api/pinterest",
//   passportConfig.isAuthenticated,
//   passportConfig.isAuthorized,
//   apiController.postPinterest
// );
app.get("/api/google-maps", apiController.getGoogleMaps);

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

/**
 * OAuth authorization routes. (API examples)
 */
// app.get("/auth/foursquare", passport.authorize("foursquare"));
// app.get(
//   "/auth/foursquare/callback",
//   passport.authorize("foursquare", { failureRedirect: "/api" }),
//   (req, res) => {
//     res.redirect("/api/foursquare");
//   }
// );
// app.get("/auth/tumblr", passport.authorize("tumblr"));
// app.get(
//   "/auth/tumblr/callback",
//   passport.authorize("tumblr", { failureRedirect: "/api" }),
//   (req, res) => {
//     res.redirect("/api/tumblr");
//   }
// );
// app.get("/auth/steam", passport.authorize("openid", { state: "SOME STATE" }));
// app.get(
//   "/auth/steam/callback",
//   passport.authorize("openid", { failureRedirect: "/login" }),
//   (req, res) => {
//     res.redirect(req.session.returnTo || "/");
//   }
// );
// app.get(
//   "/auth/pinterest",
//   passport.authorize("pinterest", { scope: "read_public write_public" })
// );
// app.get(
//   "/auth/pinterest/callback",
//   passport.authorize("pinterest", { failureRedirect: "/login" }),
//   (req, res) => {
//     res.redirect("/api/pinterest");
//   }
// );

/**
 * QUIZ ROUTES ================
 */

app.get("/quiz/word", wordController.getWords);
app.post("/quiz/word", wordController.postWord);
app.put("/quiz/word", wordController.updateWord);
app.get(
  "/quiz",
  passportConfig.isAuthenticated,
  quizController.getQuiz);
app.put("/quiz/bestword", quizController.addBestWord);
// app.get("/quiz/bestword", quizController.getBestWord);
app.delete("/quiz/bestword", removeBestWord.removeBestWord);
app.post(
  "/quiz",
  passportConfig.isAuthenticated,
  quizController.createQuiz);
app.get("/quiz/analysis", quizAnalysis.performAnalysis);
app.get(
  "/report",
  passportConfig.isAuthenticated,
  reportController.getReport
);
app.get("/comingSoon", comingSoon.index);
app.get("/profilesOverview", profilesOverview.index);

/**
 *  End QUIZ ROUTES ===============
 */

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

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

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

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

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

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

/**
 * Controllers (route handlers).
 */
const homeController = require("./controllers/home");
const userController = require("./controllers/user");
const apiController = require("./controllers/api");
const contactController = require("./controllers/contact");
const wordController = require("./controllers/word");
const quizController = require("./controllers/quiz");
const removeBestWord = require("./controllers/removebestword");
const quizAnalysis = require("./controllers/quizAnalysis");
const reportController = require("./controllers/report");
const comingSoon = require("./controllers/comingSoon");
const profilesOverview = require("./controllers/profilesOverview");

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

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

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

/**
 * Populate the Mongo Database with initial data
 * TODO: Make this dependant on the dev environment
 */
const db = require("./util/db");
console.log("Pre populate the database");
db();
console.log("Done pre-populating the database");

/**
 * Express configuration.
 */
app.set("port", process.env.PORT || 3000);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(expressStatusMonitor());
app.use(compression());
app.use(
  sass({
    src: path.join(__dirname, "public"),
    dest: path.join(__dirname, "public")
  })
);
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(
  session({
    resave: true,
    saveUninitialized: true,
    secret: process.env.SESSION_SECRET,
    store: new MongoStore({
      url: process.env.MONGODB_URI || process.env.MONGOLAB_URI,
      autoReconnect: true,
      clear_interval: 3600
    })
  })
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
  next();
  // if (req.path === '/api/upload') {
  //   next();
  // } else {
  //   lusca.csrf()(req, res, next);
  // }
});
app.use(lusca.xframe("SAMEORIGIN"));
app.use(lusca.xssProtection(true));
app.use((req, res, next) => {
  res.locals.user = req.user;
  next();
});
app.use((req, res, next) => {
  // After successful login, redirect back to the intended page
  if (
    !req.user &&
    req.path !== "/login" &&
    req.path !== "/signup" &&
    !req.path.match(/^\/auth/) &&
    !req.path.match(/\./)
  ) {
    req.session.returnTo = req.path;
  } else if (req.user && req.path === "/account") {
    req.session.returnTo = req.path;
  }
  next();
});
app.use(
  express.static(path.join(__dirname, "public"), { maxAge: 31557600000 })
);

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

/**
 * API examples routes.
 */
app.get("/api", apiController.getApi);
app.get("/api/lastfm", apiController.getLastfm);
app.get("/api/nyt", apiController.getNewYorkTimes);
app.get("/api/aviary", apiController.getAviary);
app.get(
  "/api/steam",
  passportConfig.isAuthenticated,
  passportConfig.isAuthorized,
  apiController.getSteam
);
app.get("/api/stripe", apiController.getStripe);
app.post("/api/stripe", apiController.postStripe);
app.get("/api/scraping", apiController.getScraping);
//app.get("/api/twilio", apiController.getTwilio);
//app.post("/api/twilio", apiController.postTwilio);
//app.get("/api/clockwork", apiController.getClockwork);
//app.post("/api/clockwork", apiController.postClockwork);
//app.get(
//   "/api/foursquare",
//   passportConfig.isAuthenticated,
//   passportConfig.isAuthorized,
//   apiController.getFoursquare
// );
// app.get(
//   "/api/tumblr",
//   passportConfig.isAuthenticated,
//   passportConfig.isAuthorized,
//   apiController.getTumblr
// );
app.get(
  "/api/facebook",
  passportConfig.isAuthenticated,
  passportConfig.isAuthorized,
  apiController.getFacebook
);
app.get(
  "/api/github",
  passportConfig.isAuthenticated,
  passportConfig.isAuthorized,
  apiController.getGithub
);
app.get(
  "/api/twitter",
  passportConfig.isAuthenticated,
  passportConfig.isAuthorized,
  apiController.getTwitter
);
app.post(
  "/api/twitter",
  passportConfig.isAuthenticated,
  passportConfig.isAuthorized,
  apiController.postTwitter
);
// app.get(
//   "/api/linkedin",
//   passportConfig.isAuthenticated,
//   passportConfig.isAuthorized,
//   apiController.getLinkedin
// );
// app.get(
//   "/api/instagram",
//   passportConfig.isAuthenticated,
//   passportConfig.isAuthorized,
//   apiController.getInstagram
// );
app.get("/api/paypal", apiController.getPayPal);
app.get("/api/paypal/success", apiController.getPayPalSuccess);
app.get("/api/paypal/cancel", apiController.getPayPalCancel);
app.get("/api/lob", apiController.getLob);
// app.get("/api/upload", apiController.getFileUpload);
// app.post("/api/upload", upload.single("myFile"), apiController.postFileUpload);
// app.get(
//   "/api/pinterest",
//   passportConfig.isAuthenticated,
//   passportConfig.isAuthorized,
//   apiController.getPinterest
// );
// app.post(
//   "/api/pinterest",
//   passportConfig.isAuthenticated,
//   passportConfig.isAuthorized,
//   apiController.postPinterest
// );
app.get("/api/google-maps", apiController.getGoogleMaps);

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

/**
 * OAuth authorization routes. (API examples)
 */
// app.get("/auth/foursquare", passport.authorize("foursquare"));
// app.get(
//   "/auth/foursquare/callback",
//   passport.authorize("foursquare", { failureRedirect: "/api" }),
//   (req, res) => {
//     res.redirect("/api/foursquare");
//   }
// );
// app.get("/auth/tumblr", passport.authorize("tumblr"));
// app.get(
//   "/auth/tumblr/callback",
//   passport.authorize("tumblr", { failureRedirect: "/api" }),
//   (req, res) => {
//     res.redirect("/api/tumblr");
//   }
// );
// app.get("/auth/steam", passport.authorize("openid", { state: "SOME STATE" }));
// app.get(
//   "/auth/steam/callback",
//   passport.authorize("openid", { failureRedirect: "/login" }),
//   (req, res) => {
//     res.redirect(req.session.returnTo || "/");
//   }
// );
// app.get(
//   "/auth/pinterest",
//   passport.authorize("pinterest", { scope: "read_public write_public" })
// );
// app.get(
//   "/auth/pinterest/callback",
//   passport.authorize("pinterest", { failureRedirect: "/login" }),
//   (req, res) => {
//     res.redirect("/api/pinterest");
//   }
// );

/**
 * QUIZ ROUTES ================
 */

app.get("/quiz/word", wordController.getWords);
app.post("/quiz/word", wordController.postWord);
app.put("/quiz/word", wordController.updateWord);
app.get(
  "/quiz",
  passportConfig.isAuthenticated,
  quizController.getQuiz);
app.put("/quiz/bestword", quizController.addBestWord);
// app.get("/quiz/bestword", quizController.getBestWord);
app.delete("/quiz/bestword", removeBestWord.removeBestWord);
app.post(
  "/quiz",
  passportConfig.isAuthenticated,
  quizController.createQuiz);
app.get("/quiz/analysis", quizAnalysis.performAnalysis);
app.get(
  "/report",
  passportConfig.isAuthenticated,
  reportController.getReport
);
app.get("/comingSoon", comingSoon.index);
app.get("/profilesOverview", profilesOverview.index);

/**
 *  End QUIZ ROUTES ===============
 */

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

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

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

module.exports = app;
<|endoftext|>


<commit_before>var fs = require('fs');
var blessed = require('blessed');
var multiline = require('multiline');

var screen = blessed.screen({
  autoPadding: true
});

screen.key('q', function() {
  process.exit(0);
});

var home = blessed.list({
  parent: screen,
  padding: { top: 2 },
  mouse: true,
  keys: true,
  fg: 'white',
  bg: 'blue',
  selectedFg: 'blue',
  selectedBg: 'white',
  items: [
    '» REMOVE AUTHENTICATION',
    '» CHANGE EMAIL SERVICE',
    '» ENABLE SOCKET.IO',
    '» ADD NODE.JS CLUSTER SUPPORT',
    '» EXIT'
  ]
});

var inner = blessed.form({
  top: 'center',
  left: 'center',
  mouse: true,
  keys: true,
  width: 33,
  height: 10,
  border: {
    type: 'line',
    fg: 'white',
    bg: 'red'
  },
  fg: 'white',
  bg: 'red'
});

var success = blessed.box({
  top: 'center',
  left: 'center',
  mouse: true,
  keys: true,
  tags: true,
  width: '50%',
  height: '40%',
  border: {
    type: 'line',
    fg: 'white',
    bg: 'green'
  },
  fg: 'white',
  bg: 'green',
  padding: 1
});

success.on('keypress', function() {
  home.focus();
  home.remove(success);
});

var socketText = blessed.text({
  top: 'top',
  bg: 'red',
  fg: 'white',
  tags: true,
  content: 'Add real-time support to your application with Socket.IO.'
});

var clusterText = blessed.text({
  top: 'top',
  bg: 'red',
  fg: 'white',
  tags: true,
  content: 'Take advantage of multi-core systems using built-in {underline}cluster{/underline} module.'
});

var enable = blessed.button({
  parent: inner,
  bottom: 0,
  mouse: true,
  shrink: true,
  name: 'enable',
  content: ' ENABLE ',
  border: {
    type: 'line',
    fg: 'white',
    bg: 'red'
  },
  style: {
    fg: 'white',
    bg: 'red',
    focus: {
      fg: 'red',
      bg: 'white'
    }
  }
});

var disable = blessed.button({
  parent: inner,
  bottom: 0,
  left: 10,
  mouse: true,
  shrink: true,
  name: 'disable',
  content: ' DISABLE ',
  border: {
    type: 'line',
    fg: 'white',
    bg: 'red'
  },
  style: {
    fg: 'white',
    bg: 'red',
    focus: {
      fg: 'red',
      bg: 'white'
    }
  }
});

var cancel = blessed.button({
  parent: inner,
  bottom: 0,
  left: 21,
  mouse: true,
  shrink: true,
  name: 'cancel',
  content: ' CANCEL ',
  border: {
    type: 'line',
    fg: 'white',
    bg: 'red'
  },
  style: {
    fg: 'white',
    bg: 'red',
    focus: {
      fg: 'red',
      bg: 'white'
    }
  }
});

cancel.on('press', function() {
  home.focus();
  home.remove(inner);
  screen.render();

});

var auth = blessed.form({
  mouse: true,
  keys: true,
  fg: 'white',
  bg: 'blue',
  padding: { left: 1, right: 1 }
});

var authText = blessed.text({
  parent: auth,
  content: 'Selecting a checkbox adds an authentication provider. Unselecting a checkbox removes it. If authentication provider is already present, no action will be taken.',
  padding: 1,
  bg: 'magenta',
  fg: 'white'
});

var facebookCheckbox = blessed.checkbox({
  parent: auth,
  top: 6,
  checked: true,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'Facebook'
});

var githubCheckbox = blessed.checkbox({
  parent: auth,
  top: 7,
  checked: true,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'GitHub'
});

var googleCheckbox = blessed.checkbox({
  parent: auth,
  top: 8,
  checked: true,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'Google'
});

var twitterCheckbox = blessed.checkbox({
  parent: auth,
  top: 9,
  checked: true,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'Twitter'
});

var linkedinCheckbox = blessed.checkbox({
  parent: auth,
  top: 10,
  checked: true,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'LinkedIn'
});

var instagramCheckbox = blessed.checkbox({
  parent: auth,
  top: 11,
  checked: true,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'Instagram'
});

var authSubmit = blessed.button({
  parent: auth,
  top: 13,
  mouse: true,
  shrink: true,
  name: 'submit',
  content: ' SUBMIT ',
  style: {
    fg: 'blue',
    bg: 'white',
    focus: {
      fg: 'white',
      bg: 'red'
    }
  }
});

var authCancel = blessed.button({
  parent: auth,
  top: 13,
  left: 9,
  mouse: true,
  shrink: true,
  name: 'cancel',
  content: ' CANCEL ',
  style: {
    fg: 'blue',
    bg: 'white',
    focus: {
      fg: 'white',
      bg: 'red'
    }
  }
});

authCancel.on('press', function() {
  home.focus();
  home.remove(auth);
  screen.render();
});

var email = blessed.form({
  mouse: true,
  keys: true,
  fg: 'white',
  bg: 'blue',
  padding: { left: 1, right: 1 }
});

var emailText = blessed.text({
  parent: email,
  content: 'Select one of the following email service providers for {underline}contact form{/underline} and {underline}password reset{/underline}.',
  padding: 1,
  bg: 'red',
  fg: 'white',
  tags: true
});

var sendgridRadio = blessed.radiobutton({
  parent: email,
  top: 5,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'SendGrid'
});

var mailgunRadio = blessed.radiobutton({
  parent: email,
  top: 6,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'Mailgun'
});

var mandrillRadio = blessed.radiobutton({
  parent: email,
  top: 7,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'Mandrill'
});

var emailOk = blessed.button({
  parent: email,
  top: 9,
  mouse: true,
  shrink: true,
  name: 'ok',
  content: ' SUBMIT ',
  style: {
    fg: 'blue',
    bg: 'white',
    focus: {
      fg: 'white',
      bg: 'red'
    }
  }
});

var emailCancel = blessed.button({
  parent: email,
  top: 9,
  left: 9,
  mouse: true,
  shrink: true,
  name: 'cancel',
  content: ' CANCEL ',
  style: {
    fg: 'blue',
    bg: 'white',
    focus: {
      fg: 'white',
      bg: 'red'
    }
  }
});

emailCancel.on('press', function() {
  home.focus();
  home.remove(email);
  screen.render();

});

var title = blessed.text({
  parent: screen,
  align: 'center',
  fg: 'blue',
  bg: 'white',
  content: 'Hackathon Starter (c) 2014'
});

var footer = blessed.text({
  parent: screen,
  bottom: 0,
  fg: 'white',
  bg: 'blue',
  tags: true,
  content: ' {cyan-fg}<Up/Down>{/cyan-fg} moves | {cyan-fg}<Enter>{/cyan-fg} selects | {cyan-fg}<q>{/cyan-fg} exits'
});

home.on('select', function(child, index) {
  switch (index) {
    case 0:
      home.append(auth);
      auth.focus();
      screen.render();
      break;
    case 1:
      home.append(email);
      email.focus();
      break;
    case 2:
      enableSocketIo();
      home.append(success);
      success.setContent('Socket.IO events have been added at the bottom of {underline}app.js{/underline}. To see a working example take a look at /dashboard. Be sure to run npm install socket.io');
      success.focus();
      screen.render();
      break;
    case 3:
      // Cluster
      addClusterSupport();
      home.append(success);
      success.setContent('New file {underline}cluster_app.js{/underline} has been created. Your app is now able to use more than 1 CPU by running {underline}node cluster_app.js{/underline}, which in turn spawns multiple instances of {underline}app.js{/underline}');
      success.focus();
      screen.render();
      break;
    default:
      process.exit(0);
  }
});

screen.render();

function addClusterSupport() {

  var fileContents = multiline(function() {
/*
var os = require('os');
var cluster = require('cluster');

cluster.setupMaster({
  exec: 'app.js'
});

cluster.on('exit', function(worker) {
  console.log('worker ' + worker.id + ' died');
  cluster.fork();
});

for (var i = 0; i < os.cpus().length; i++) {
  cluster.fork();
}
*/
  });

  fs.writeFileSync('cluster_app.js', fileContents);
}

function enableSocketIo() {
  var fileContents = multiline(function() {
    /*

     */
  });
}<commit_msg>Email Service generator<commit_after>var fs = require('fs');
var os = require('os');
var blessed = require('blessed');
var multiline = require('multiline');

var screen = blessed.screen({
  autoPadding: true
});

screen.key('q', function() {
  process.exit(0);
});

var home = blessed.list({
  parent: screen,
  padding: { top: 2 },
  mouse: true,
  keys: true,
  fg: 'white',
  bg: 'blue',
  selectedFg: 'blue',
  selectedBg: 'white',
  items: [
    '» REMOVE AUTHENTICATION',
    '» CHANGE EMAIL SERVICE',
    '» ENABLE SOCKET.IO',
    '» ADD NODE.JS CLUSTER SUPPORT',
    '» EXIT'
  ]
});

var inner = blessed.form({
  top: 'center',
  left: 'center',
  mouse: true,
  keys: true,
  width: 33,
  height: 10,
  border: {
    type: 'line',
    fg: 'white',
    bg: 'red'
  },
  fg: 'white',
  bg: 'red'
});

var success = blessed.box({
  top: 'center',
  left: 'center',
  mouse: true,
  keys: true,
  tags: true,
  width: '50%',
  height: '40%',
  border: {
    type: 'line',
    fg: 'white',
    bg: 'green'
  },
  fg: 'white',
  bg: 'green',
  padding: 1
});

success.on('keypress', function() {
  home.focus();
  home.remove(success);
});

var socketText = blessed.text({
  top: 'top',
  bg: 'red',
  fg: 'white',
  tags: true,
  content: 'Add real-time support to your application with Socket.IO.'
});

var clusterText = blessed.text({
  top: 'top',
  bg: 'red',
  fg: 'white',
  tags: true,
  content: 'Take advantage of multi-core systems using built-in {underline}cluster{/underline} module.'
});

var enable = blessed.button({
  parent: inner,
  bottom: 0,
  mouse: true,
  shrink: true,
  name: 'enable',
  content: ' ENABLE ',
  border: {
    type: 'line',
    fg: 'white',
    bg: 'red'
  },
  style: {
    fg: 'white',
    bg: 'red',
    focus: {
      fg: 'red',
      bg: 'white'
    }
  }
});

var disable = blessed.button({
  parent: inner,
  bottom: 0,
  left: 10,
  mouse: true,
  shrink: true,
  name: 'disable',
  content: ' DISABLE ',
  border: {
    type: 'line',
    fg: 'white',
    bg: 'red'
  },
  style: {
    fg: 'white',
    bg: 'red',
    focus: {
      fg: 'red',
      bg: 'white'
    }
  }
});

var cancel = blessed.button({
  parent: inner,
  bottom: 0,
  left: 21,
  mouse: true,
  shrink: true,
  name: 'cancel',
  content: ' CANCEL ',
  border: {
    type: 'line',
    fg: 'white',
    bg: 'red'
  },
  style: {
    fg: 'white',
    bg: 'red',
    focus: {
      fg: 'red',
      bg: 'white'
    }
  }
});

cancel.on('press', function() {
  home.focus();
  home.remove(inner);
  screen.render();

});

var auth = blessed.form({
  mouse: true,
  keys: true,
  fg: 'white',
  bg: 'blue',
  padding: { left: 1, right: 1 }
});

var authText = blessed.text({
  parent: auth,
  content: 'Selecting a checkbox adds an authentication provider. Unselecting a checkbox removes it. If authentication provider is already present, no action will be taken.',
  padding: 1,
  bg: 'magenta',
  fg: 'white'
});

var facebookCheckbox = blessed.checkbox({
  parent: auth,
  top: 6,
  checked: true,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'Facebook'
});

var githubCheckbox = blessed.checkbox({
  parent: auth,
  top: 7,
  checked: true,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'GitHub'
});

var googleCheckbox = blessed.checkbox({
  parent: auth,
  top: 8,
  checked: true,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'Google'
});

var twitterCheckbox = blessed.checkbox({
  parent: auth,
  top: 9,
  checked: true,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'Twitter'
});

var linkedinCheckbox = blessed.checkbox({
  parent: auth,
  top: 10,
  checked: true,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'LinkedIn'
});

var instagramCheckbox = blessed.checkbox({
  parent: auth,
  top: 11,
  checked: true,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'Instagram'
});

var authSubmit = blessed.button({
  parent: auth,
  top: 13,
  mouse: true,
  shrink: true,
  name: 'submit',
  content: ' SUBMIT ',
  style: {
    fg: 'blue',
    bg: 'white',
    focus: {
      fg: 'white',
      bg: 'red'
    }
  }
});

var authCancel = blessed.button({
  parent: auth,
  top: 13,
  left: 9,
  mouse: true,
  shrink: true,
  name: 'cancel',
  content: ' CANCEL ',
  style: {
    fg: 'blue',
    bg: 'white',
    focus: {
      fg: 'white',
      bg: 'red'
    }
  }
});

authCancel.on('press', function() {
  home.focus();
  home.remove(auth);
  screen.render();
});

var emailForm = blessed.form({
  mouse: true,
  keys: true,
  fg: 'white',
  bg: 'blue',
  padding: { left: 1, right: 1 }
});

emailForm.on('submit', function(data) {
  var contactCtrl = fs.readFileSync('controllers/contact.js').toString().split(os.EOL);
  var userCtrl = fs.readFileSync('controllers/user.js').toString().split(os.EOL);
  var choice = null;

  if (sendgridRadio.checked) {
    choice = 'SendGrid';
  } else if (mailgunRadio.checked) {
    choice = 'Mailgun';
  } else if (mandrillRadio.checked) {
    choice = 'Mandrill';
  }

  var index = contactCtrl.indexOf('var smtpTransport = nodemailer.createTransport(\'SMTP\', {');
  contactCtrl.splice(index + 1, 1, "  service: '" + choice + "',");
  contactCtrl.splice(index + 3, 1, '       user: secrets.' + choice.toLowerCase() +'.user,');
  contactCtrl.splice(index + 4, 1, '       pass: secrets.' + choice.toLowerCase() + '.password');
  fs.writeFileSync('controllers/contact.js', contactCtrl.join(os.EOL));

  index = userCtrl.indexOf('      var smtpTransport = nodemailer.createTransport(\'SMTP\', {');
  userCtrl.splice(index + 1, 1, "        service: '" + choice + "',");
  userCtrl.splice(index + 3, 1, '          user: secrets.' + choice.toLowerCase() + '.user,');
  userCtrl.splice(index + 4, 1, '          pass: secrets.' + choice.toLowerCase() + '.password');
  index = userCtrl.indexOf('      var smtpTransport = nodemailer.createTransport(\'SMTP\', {', (index + 1));
  userCtrl.splice(index + 1, 1, "        service: '" + choice + "',");
  userCtrl.splice(index + 3, 1, '          user: secrets.' + choice.toLowerCase() + '.user,');
  userCtrl.splice(index + 4, 1, '          pass: secrets.' + choice.toLowerCase() + '.password');
  fs.writeFileSync('controllers/user.js', userCtrl.join(os.EOL));

  home.remove(emailForm);
  home.append(success);
  success.setContent('Email Service has been switched to ' + choice);
  success.focus();
  screen.render();
});

var emailText = blessed.text({
  parent: emailForm,
  content: 'Select one of the following email service providers for {underline}contact form{/underline} and {underline}password reset{/underline}.',
  padding: 1,
  bg: 'red',
  fg: 'white',
  tags: true
});

var sendgridRadio = blessed.radiobutton({
  parent: emailForm,
  top: 5,
  checked: true,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'SendGrid'
});

var mailgunRadio = blessed.radiobutton({
  parent: emailForm,
  top: 6,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'Mailgun'
});

var mandrillRadio = blessed.radiobutton({
  parent: emailForm,
  top: 7,
  mouse: true,
  fg: 'white',
  bg: 'blue',
  content: 'Mandrill'
});

var emailSubmit = blessed.button({
  parent: emailForm,
  top: 9,
  mouse: true,
  shrink: true,
  name: 'submit',
  content: ' SUBMIT ',
  style: {
    fg: 'blue',
    bg: 'white',
    focus: {
      fg: 'white',
      bg: 'red'
    }
  }
});

emailSubmit.on('press', function() {
  emailForm.submit();
});

var emailCancel = blessed.button({
  parent: emailForm,
  top: 9,
  left: 9,
  mouse: true,
  shrink: true,
  name: 'cancel',
  content: ' CANCEL ',
  style: {
    fg: 'blue',
    bg: 'white',
    focus: {
      fg: 'white',
      bg: 'red'
    }
  }
});

emailCancel.on('press', function() {
  home.focus();
  home.remove(emailForm);
  screen.render();

});

var title = blessed.text({
  parent: screen,
  align: 'center',
  fg: 'blue',
  bg: 'white',
  content: 'Hackathon Starter (c) 2014'
});

var footer = blessed.text({
  parent: screen,
  bottom: 0,
  fg: 'white',
  bg: 'blue',
  tags: true,
  content: ' {cyan-fg}<Up/Down>{/cyan-fg} moves | {cyan-fg}<Enter>{/cyan-fg} selects | {cyan-fg}<q>{/cyan-fg} exits'
});

home.on('select', function(child, index) {
  switch (index) {
    case 0:
      home.append(auth);
      auth.focus();
      screen.render();
      break;
    case 1:
      home.append(emailForm);
      emailForm.focus();
      break;
    case 2:
      enableSocketIo();
      home.append(success);
      success.setContent('Socket.IO events have been added at the bottom of {underline}app.js{/underline}. To see a working example take a look at /dashboard. Be sure to run npm install socket.io');
      success.focus();
      screen.render();
      break;
    case 3:
      addClusterSupport();
      home.append(success);
      success.setContent('New file {underline}cluster_app.js{/underline} has been created. Your app is now able to use more than 1 CPU by running {underline}node cluster_app.js{/underline}, which in turn spawns multiple instances of {underline}app.js{/underline}');
      success.focus();
      screen.render();
      break;
    default:
      process.exit(0);
  }
});

screen.render();

function addClusterSupport() {

  var fileContents = multiline(function() {
/*
var os = require('os');
var cluster = require('cluster');

cluster.setupMaster({
  exec: 'app.js'
});

cluster.on('exit', function(worker) {
  console.log('worker ' + worker.id + ' died');
  cluster.fork();
});

for (var i = 0; i < os.cpus().length; i++) {
  cluster.fork();
}
*/
  });

  fs.writeFileSync('cluster_app.js', fileContents);
}

function enableSocketIo() {
  var fileContents = multiline(function() {
    /*

     */
  });
}<|endoftext|>


<commit_before>var $ = require('jquery');
var html = $(
'
' +
    '
Are you sure you want to revert this file?
' +
    '

' +
    '
' +
        '<button class="inline-block-tight btn btn-lg cancel">Cancel</button>' +
        '<button class="inline-block-tight btn btn-lg btn-error yes icon icon-zap">Revert</button>' +
    '
' +
'
'
);
var panel;
var editor;
var destroyPanel = function () {
    if (panel) {
        panel.destroy();
    }
    if (editor) {
        $(editor.editorElement).removeClass('git-revert-active');
    }
};
var revert = function (path) {
    var currentPath;
    if (path) {
        currentPath = path;
    } else {
        editor = atom.workspace.getActiveTextEditor();
        currentPath = editor.getPath();
    }
    var repo = atom.project.getRepositories()[0];
    if (!repo || !currentPath) {
        return;
    }
    var repoPath = repo.path.replace('.git', ''),
        status = repo.statuses[currentPath.replace(repoPath, '')];

    if (status) {
        if (editor) {
            $(editor.editorElement).addClass('git-revert-active');
        }
        panel = atom.workspace.addModalPanel({
            item: html
        });

        //set filename
        html.find('.git-revert-filename').text(currentPath);

        html.off('click');
        html.on('click', '.btn', function (e) {
            destroyPanel();
            if ($(e.target).hasClass('yes')) {
                //is 0 always good?
                var reverted = repo.checkoutHead(currentPath);
                if (reverted) {
                    atom.notifications.addSuccess('File ' + currentPath + ' reverted!');
                }
            }
        });
    } else {
        atom.notifications.addInfo('File ' + currentPath + ' is in sync with HEAD!');
    }
};

module.exports = {
    activate: function () {
        atom.commands.add('atom-text-editor', 'git-revert:revert', function () {
            revert();
        });
        atom.commands.add('atom-text-editor', 'git-revert:close', function () {
            if (panel) {
                destroyPanel();
            }
        });
        atom.commands.add('.tree-view', 'git-revert:revert', function (event) {
            var path = event.target.getAttribute('data-path');
            revert(path);
        });
    }
};
<commit_msg>make it work when you have other project folders<commit_after>var $ = require('jquery');
var html = $(
'
' +
    '
Are you sure you want to revert this file?
' +
    '

' +
    '
' +
        '<button class="inline-block-tight btn btn-lg cancel">Cancel</button>' +
        '<button class="inline-block-tight btn btn-lg btn-error yes icon icon-zap">Revert</button>' +
    '
' +
'
'
);
var panel;
var editor;
var destroyPanel = function () {
    html.off('click');
    if (panel) {
        panel.destroy();
    }
    if (editor) {
        $(editor.editorElement).removeClass('git-revert-active');
    }
};
var revert = function (path) {
    var useThisRepo = -1,
        repos = atom.project.getRepositories(),
        currentPath,
        justFilePath;

    if (path) {
        //if we supplied a path use it straight up
        currentPath = path;
    } else {
        //else find the editor with focus and use that file
        editor = atom.workspace.getActiveTextEditor();
        currentPath = editor.getPath();
    }
    debugger;

    if (!currentPath) { return; }

    $.each(repos, function (i, _repo) {
        if (!_repo) { // null, non git dir
            return;
        }

        var tpath = _repo.getWorkingDirectory() + '/',
            tfile = currentPath.replace(tpath, '');
        //if this file in git statuses is dirty, this must be our repo
        if (_repo && tfile in _repo.statuses) {
            useThisRepo = i;
        }
    });

    //found no git repos, nothing to do
    if (useThisRepo < 0) { return; }

    var repo = atom.project.getRepositories()[useThisRepo];

    //redoing some computations we just did
    var repoPath = repo.getWorkingDirectory() + '/',
        justFilePath = currentPath.replace(repoPath, '');

    var status = repo.statuses[justFilePath];

    if (!repo) {
        return;
    }

    if (status) {
        if (editor) {
            $(editor.editorElement).addClass('git-revert-active');
        }
        panel = atom.workspace.addModalPanel({
            item: html
        });

        //set filename
        html.find('.git-revert-filename').text(currentPath);

        html.off('click');
        html.on('click', '.btn', function (e) {
            destroyPanel();
            if ($(e.target).hasClass('yes')) {
                //is 0 always good?
                var reverted = repo.checkoutHead(currentPath);
                if (reverted) {
                    atom.notifications.addSuccess('File ' + currentPath + ' reverted!');
                }
            }
        });
    } else {
        atom.notifications.addInfo('File ' + currentPath + ' is in sync with HEAD!');
    }
};

module.exports = {
    activate: function () {
        atom.commands.add('atom-text-editor', 'git-revert:revert', function () {
            revert();
        });
        atom.commands.add('atom-text-editor', 'git-revert:close', function () {
            if (panel) {
                destroyPanel();
            }
        });
        atom.commands.add('.tree-view', 'git-revert:revert', function (event) {
            var path = event.target.getAttribute('data-path');
            revert(path);
        });
    }
};
<|endoftext|>


<commit_before>require('dotenv').load();
var fs          = require('fs'),
    path        = require('path'),
    readline    = require('readline'),
    colors      = require('colors'),
    pizzapi     = require('dominos'),
    dash_button = require('node-dash-button'),
    util        = require('util');

colors.setTheme(
    {
        menuItem    : 'bgCyan',
        menuTitle   : 'bgBlue',
        store       : 'bgBlue',
        info        : 'cyan'
    }
);

var rl = readline.createInterface(
    {
        input: process.stdin,
        output: process.stdout,
        terminal:true
    }
);
process.stdin.setEncoding('utf8');

readline.cursorTo(process.stdout, 0, 0);
readline.clearScreenDown(process.stdout);

rl.setPrompt('Pizza Dash> ');
rl.prompt();

var order=new pizzapi.Order();

rl.on(
    'line',
    function(chunk) {
        chunk=chunk.trim();

        if (chunk !== null) {
            chunk = chunk.replace( /\s\s+/g, ' ' ).trim();

            var data = chunk.toLowerCase();

            if(data.indexOf('find near ')>-1){
                findStores(data.slice(10));
                return;
            }

            if(data.indexOf('find closest ')>-1){
                findStores(data.slice(data.indexOf('find closest ')+13),true);
                return;
            }

            if(data.indexOf('full menu for closest')>-1){
                findStores(data.slice(data.indexOf('full menu for closest')+21),true,false,true);
                return;
            }

            if(data.indexOf('menu for closest')>-1){
                findStores(data.slice(data.indexOf('menu for closest')+16),true,true);
                return;
            }

            if(data.indexOf('full menu for ')>-1){
                showMenu(data.slice(data.indexOf('full menu for ')+14));
                return;
            }

            if(data.indexOf('menu for ')>-1){
                showMenu(data.slice(data.indexOf('menu for ')+9),true);
                return;
            }

            if(data.indexOf('order ')>-1){
                orderPizza(data.slice(data.indexOf('order ')+6),true);
                return;
            }

            //Find Button
            if(data.indexOf('find button')>-1){
                return;
            }
            //Set Order (name)
            if(data.indexOf('set order ')>-1){
                return;
            }
            //Set button mac_address ordername
            if(data.indexOf('set order ')>-1){
                return;
            }
            if(data.indexOf('help')>-1){
                help();
                return;
            }

            rl.prompt();
        }
    }
);

function help(){
    var commands=[
        'find closest'.bgCyan+' {address info}'.info+' can be full or partial address city and state, postal code etc...',
        'find near'.bgCyan+' {address info}'.info+' can be full or partial address city and state, postal code etc...',
        'menu for closest'.bgCyan+' {address info}'.info+' can be full or partital address city and state, postal code etc...',
        'full menu for closest'.bgCyan+' {address info}'.info+' can be full or partial address city and state, postal code etc...',
        'menu for'.bgCyan+' {storeID}'.info+' get store id as part of a find closest or find near request',
        'full menu for'.bgCyan+' {storeID}'.info+' get store id as part of a find closest or find near request',
        'order'.bgCyan+' {comma deliminated list of item codes} \nexample:\norder PXC_14SCREEN, 2LSPRITE'.info+' !!!!get item codes from menu'
    ];

    for(var i in commands){
        console.log(commands[i]+'\n');
    }
}

/*
 * pass in pizza info
 *
 */

function showMenu(storeID,quick){
    console.log('Fetching menu for '+storeID.info+'...');
    order.StoreID=storeID
    rl.prompt();

    var store=new pizzapi.Store(
        {
            ID:storeID
        }
    );

    store.getMenu(
        function(data){
            if(quick){
                console.log(
                    '\n##########################\n'.blue,
                    'Quick Menu'.yellow,
                    '\n##########################\n'.blue
                );
                for(var i in data.result.PreconfiguredProducts){
                    var item=data.result.PreconfiguredProducts[i];
                    console.log(
                        '\n'.blue+
                        (
                            (
                                item.Name.bold+' : '+
                                item.Code+'\n'
                            ).menuTitle+
                            item.Description+'\n'+
                            item.Size
                        ).menuItem.white
                    );
                };

                rl.prompt();
                return;
            }

            console.log(
                '\n##########################\n'.blue,
                'Full Menu'.yellow,
                '\n##########################\n'.blue
            );

            var menuPortions=[
                'Sides',
                'PreconfiguredProducts',
                'Products'
            ];

            for(var j in menuPortions){
                for(var i in data.result[menuPortions[j]]){
                    if(!data.result[menuPortions[j]][i].Name){
                        console.log(
                            (
                                '=========='.cyan+
                                i.blue+
                                '=========='.cyan
                            ).bgYellow
                        );

                        for(var k in data.result[menuPortions[j]][i]){
                            var item=data.result[menuPortions[j]][i][k];
                            console.log(
                                '(+)'+(
                                    (
                                        item.Name.bold+' : '+
                                        item.Code+'\n'
                                    ).menuTitle+
                                    item.Description+'\n'+
                                    item.Size
                                ).menuItem.white
                            );
                        }
                        continue;
                    }
                    var item=data.result[menuPortions[j]][i];
                    console.log(
                        '(+)'+(
                            (
                                item.Name.bold+' : '+
                                item.Code+'\n'
                            ).menuTitle+
                            item.Description+'\n'+
                            item.Size
                        ).menuItem.white
                    );
                };
            }
            rl.prompt();
        }
    );
}

function validateAddress(address){
    var address=new pizzapi.Address(address);
    pizzapi.Util.findNearbyStores(
        address,
        function(storeData){
            order.Address=storeData.result.Address;
            if(!order.Address.Street){
                rl.question(
                    'Not a valid address.'.red
                    +' if your having trouble, try using this format :\n'+'street, city, state, zip'.info+' with the commas.\n\n'
                    +'What is the full address for delivery?\n ',
                    validateAddress
                );
                return;
            }

            if(!order.StoreID){
                console.log(
                    'You have not viewed any store\'s Menu, so you will get your order from the closest open store which delivers.\n'
                    +'And you\'ll like it!'.red
                );
            }

            pizzapi.Util.findNearbyStores(
                order.Address,
                'Delivery',
                function(storeData){
                    var openStores=[];

                    for(var i in storeData.result.Stores){
                        if(storeData.result.Stores[i].IsOpen &&
                            storeData.result.Stores[i].IsOnlineNow &&
                            storeData.result.Stores[i].ServiceIsOpen.Delivery
                        ){
                            order.StoreID=storeData.result.Stores[i].StoreID;
                            break;
                        }
                    }

                    if(!order.StoreID){
                        console.log('No Open Stores allowing delivery right now for the specified location'.bgRed.black.bold);
                        throw('NO PIZZA FOR YOU! Look at a menu next time!');
                        return;
                    }
                }
            );

            validateOrder();
        }
    );
}

function findStores(address, closest, menu, fullMenu){
    if(!address){
        console.log('Need to know where to look, please provide atleast a zip code');
        rl.prompt();
        return;
    }
    console.log('Looking for stores near '+address.info+'...');
    rl.prompt();
    var nearAddress=new pizzapi.Address(process.env.ADDRESS);

    if(!nearAddress.PostalCode){
        console.log('Not a valid address'.red+' you must at least provide a zipcode');
        return;
    }
    pizzapi.Util.findNearbyStores(
        nearAddress,
        'Delivery',
        function(storeData){
            var openStores=[];

            order.Address=new pizzapi.Address(storeData.result.Address);

            for(var i in storeData.result.Stores){
                if(storeData.result.Stores[i].IsOpen &&
                    storeData.result.Stores[i].IsOnlineNow &&
                    storeData.result.Stores[i].ServiceIsOpen.Delivery
                ){
                    openStores.push(storeData.result.Stores[i]);
                }
            }

            if(openStores.length<1){
                console.log('No Open Stores allowing delivery right now for the specified location'.bgRed.black.bold);
                return;
            }

            var count=openStores.length;

            if(closest){
                count=1;
                order.StoreID=openStores[0].StoreID
            }
            console.log('\n');
            for(var i=0; i<count; i++){
                var store=openStores[i];

                console.log(
                    '###############################################################\n'.blue+
                    (
                        'StoreID : '+store.StoreID.bold+
                        '\nAddress : '+store.AddressDescription+
                        '\nPhone : '+store.Phone+
                        '\nDelivery Hours : '+store.ServiceHoursDescription.Delivery
                    ).store.white
                );
            }

            rl.prompt();

            if(!menu && !fullMenu)
                return;

            if(menu){
                showMenu(
                    openStores[0].StoreID,
                    true
                );
                rl.prompt();
                return;
            }

            if(fullMenu){
                showMenu(
                    openStores[0].StoreID
                );
                return;
            }
        }
    );
}

function orderPizza(items){
    var items=items.split(',');
    for(var i=0; i<items.length; i++){
        //create a new item to add to the order
        order.addItem(
            new pizzapi.Item(
                {
                    code: items[i].trim(),
                    options: [],
                    quantity: 1
                }
            )
        );
    }

    if(!order.Address.Street){
        rl.question(
            'what is the full address for delivery? ',
            validateAddress
        );
        return;
    }

    validateOrder();
}

function validateOrder(){
    //console.log('validating order');
    if(!order.FirstName){
        setTimeout(
            function(){
                rl.question(
                    'First Name? ',
                    function(data){
                        order.FirstName=data;
                        validateOrder();
                    }
                );
            },100
        );
        return;
    }

    if(!order.LastName){
        rl.question(
            'Last Name? ',
            function(data){
                order.LastName=data;
                validateOrder();
            }
        );
        return;
    }

    if(!order.Email){
        rl.question(
            'E-Mail? ',
            function(data){
                order.Email=data;
                validateOrder();
            }
        );
        return;
    }

    if(!order.Phone){
        rl.question(
            'Phone number? ',
            function(data){
                order.Phone=data;
                validateOrder();
            }
        );
        return;
    }

    order.validate(orderValidated);
}

function orderValidated(){
    order.price(pricedOrder);
}

function pricedOrder() {

    var cardInfo = new order.PaymentObject();
    cardInfo.Amount = order.Amounts.Customer;
    order.Payments.push(cardInfo);

    placeOrder();
}

// function validateCC(number){
//     var re = {
//         visa        : /^4[0-9]{12}(?:[0-9]{3})?$/,
//         mastercard  : /^5[1-5][0-9]{14}$/,
//         amex        : /^3[47][0-9]{13}$/,
//         diners      : /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,
//         discover    : /^6(?:011|5[0-9]{2})[0-9]{12}$/,
//         jcb         : /^(?:2131|1800|35\d{3})\d{11}$/,
//         enroute     : /^(?:2014|2149)\d{11}$/
//     };
//
//     if (re.visa.test(number))
//         return 'VISA';
//
//     if (re.mastercard.test(number))
//         return 'MASTERCARD';
//
//     if (re.amex.test(number))
//         return 'AMEX';
//
//     if (re.diners.test(number))
//         return 'DINERS';
//
//     if (re.discover.test(number))
//         return 'DISCOVER';
//
//     if (re.jcb.test(number))
//         return 'JCB';
//
//     if (re.enroute.test(number))
//         return 'JCB';
//
//     return "";
// }

function placeOrder(){
    if(!order.Payments[0].Number){
        rl.question(
            'Credit Card Number? ',
            function(data){
                order.Payments[0].Number = data;
                order.Payments[0].CardType = order.validateCC(data);
                placeOrder();
            }
        );
        return;
    }

    if(!order.Payments[0].Expiration){
        rl.question(
            'Credit Card Expiration? ',
            function(data){
                order.Payments[0].Expiration = data.replace(/\D/g,'');
                placeOrder();
            }
        );
        return;
    }

    if(!order.Payments[0].SecurityCode){
        rl.question(
            'Credit Card Security Code or CVV (3 or 4 digit code on card)? ',
            function(data){
                order.Payments[0].SecurityCode = data;
                placeOrder();
            }
        );
        return;
    }

    if(!order.Payments[0].PostalCode){
        rl.question(
            'Postal Code? ',
            function(data){
                order.Payments[0].PostalCode = data;
                placeOrder();
            }
        );
        rl.write(order.Address.PostalCode);
        return;
    }

    order.place(orderPlaced);
}

function orderPlaced(data){
    if(data.result.Order.Status==-1){
        console.log('You\'r order failed to process.');
        if(data.result.Order.StatusItems){
            for(var i in data.result.Order.StatusItems){
                console.log(data.result.Order.StatusItems[i]);
            }
        }
        console.log('Corrective Actions from Domino\'s Pizza : '+data.result.CorrectiveAction);

        rl.prompt();
        return;
    }

    trackOrder();
}

function trackOrder(){
    pizzapi.Track.orderKey(
        order.OrderID,
        order.StoreID,
        function(pizzaData){
            readline.cursorTo(process.stdout, 0, 0);
            readline.clearScreenDown(process.stdout);

            console.log(JSON.stringify(pizzaData.orders));
            setTimeout(
                trackOrder,
                15000
            );
        }
    );
}
<commit_msg>Added setup tweaks<commit_after>require('dotenv').load();
var fs          = require('fs'),
    path        = require('path'),
    readline    = require('readline'),
    colors      = require('colors'),
    pizzapi     = require('dominos'),
    dash_button = require('node-dash-button'),
    util        = require('util');

colors.setTheme(
    {
        menuItem    : 'bgCyan',
        menuTitle   : 'bgBlue',
        store       : 'bgBlue',
        info        : 'cyan'
    }
);

var rl = readline.createInterface(
    {
        input: process.stdin,
        output: process.stdout,
        terminal:true
    }
);
process.stdin.setEncoding('utf8');

readline.cursorTo(process.stdout, 0, 0);
readline.clearScreenDown(process.stdout);

rl.setPrompt('Pizza Dash> ');
rl.prompt();

var order=new pizzapi.Order();

rl.on(
    'line',
    function(chunk) {
        chunk=chunk.trim();

        if (chunk !== null) {
            chunk = chunk.replace( /\s\s+/g, ' ' ).trim();

            var data = chunk.toLowerCase();

            if(data.indexOf('find near ')>-1){
                findStores(data.slice(10));
                return;
            }

            if(data.indexOf('find closest ')>-1){
                findStores(data.slice(data.indexOf('find closest ')+13),true);
                return;
            }

            if(data.indexOf('full menu for closest')>-1){
                findStores(data.slice(data.indexOf('full menu for closest')+21),true,false,true);
                return;
            }

            if(data.indexOf('menu for closest')>-1){
                findStores(data.slice(data.indexOf('menu for closest')+16),true,true);
                return;
            }

            if(data.indexOf('full menu for ')>-1){
                showMenu(data.slice(data.indexOf('full menu for ')+14));
                return;
            }

            if(data.indexOf('menu for ')>-1){
                showMenu(data.slice(data.indexOf('menu for ')+9),true);
                return;
            }

            if(data.indexOf('order ')>-1){
                orderPizza(data.slice(data.indexOf('order ')+6),true);
                return;
            }

            //Find Button
            if(data.indexOf('find button')>-1){
                return;
            }
            //Set Order (name)
            if(data.indexOf('set order ')>-1){
                return;
            }
            //Set button mac_address ordername
            if(data.indexOf('set button ')>-1){
                return;
            }
            if(data.indexOf('help')>-1){
                help();
                return;
            }

            rl.prompt();
        }
    }
);

function help(){
    var commands=[
        'find closest'.bgCyan+' {address info}'.info+' can be full or partial address city and state, postal code etc...',
        'find near'.bgCyan+' {address info}'.info+' can be full or partial address city and state, postal code etc...',
        'menu for closest'.bgCyan+' {address info}'.info+' can be full or partital address city and state, postal code etc...',
        'full menu for closest'.bgCyan+' {address info}'.info+' can be full or partial address city and state, postal code etc...',
        'menu for'.bgCyan+' {storeID}'.info+' get store id as part of a find closest or find near request',
        'full menu for'.bgCyan+' {storeID}'.info+' get store id as part of a find closest or find near request',
        'order'.bgCyan+' {comma deliminated list of item codes} \nexample:\norder PXC_14SCREEN, 2LSPRITE'.info+' !!!!get item codes from menu'
    ];

    for(var i in commands){
        console.log(commands[i]+'\n');
    }
}

/*
 * pass in pizza info
 *
 */

function showMenu(storeID,quick){
    console.log('Fetching menu for '+storeID.info+'...');
    order.StoreID=storeID
    rl.prompt();

    var store=new pizzapi.Store(
        {
            ID:storeID
        }
    );

    store.getMenu(
        function(data){
            if(quick){
                console.log(
                    '\n##########################\n'.blue,
                    'Quick Menu'.yellow,
                    '\n##########################\n'.blue
                );
                for(var i in data.result.PreconfiguredProducts){
                    var item=data.result.PreconfiguredProducts[i];
                    console.log(
                        '\n'.blue+
                        (
                            (
                                item.Name.bold+' : '+
                                item.Code+'\n'
                            ).menuTitle+
                            item.Description+'\n'+
                            item.Size
                        ).menuItem.white
                    );
                };

                rl.prompt();
                return;
            }

            console.log(
                '\n##########################\n'.blue,
                'Full Menu'.yellow,
                '\n##########################\n'.blue
            );

            var menuPortions=[
                'Sides',
                'PreconfiguredProducts',
                'Products'
            ];

            for(var j in menuPortions){
                for(var i in data.result[menuPortions[j]]){
                    if(!data.result[menuPortions[j]][i].Name){
                        console.log(
                            (
                                '=========='.cyan+
                                i.blue+
                                '=========='.cyan
                            ).bgYellow
                        );

                        for(var k in data.result[menuPortions[j]][i]){
                            var item=data.result[menuPortions[j]][i][k];
                            console.log(
                                '(+)'+(
                                    (
                                        item.Name.bold+' : '+
                                        item.Code+'\n'
                                    ).menuTitle+
                                    item.Description+'\n'+
                                    item.Size
                                ).menuItem.white
                            );
                        }
                        continue;
                    }
                    var item=data.result[menuPortions[j]][i];
                    console.log(
                        '(+)'+(
                            (
                                item.Name.bold+' : '+
                                item.Code+'\n'
                            ).menuTitle+
                            item.Description+'\n'+
                            item.Size
                        ).menuItem.white
                    );
                };
            }
            rl.prompt();
        }
    );
}

function validateAddress(address){
    var address=new pizzapi.Address(address);
    pizzapi.Util.findNearbyStores(
        address,
        function(storeData){
            order.Address=storeData.result.Address;
            if(!order.Address.Street){
                rl.question(
                    'Not a valid address.'.red
                    +' if your having trouble, try using this format :\n'+'street, city, state, zip'.info+' with the commas.\n\n'
                    +'What is the full address for delivery?\n ',
                    validateAddress
                );
                return;
            }

            if(!order.StoreID){
                console.log(
                    'You have not viewed any store\'s Menu, so you will get your order from the closest open store which delivers.\n'
                    +'And you\'ll like it!'.red
                );
            }

            pizzapi.Util.findNearbyStores(
                order.Address,
                'Delivery',
                function(storeData){
                    var openStores=[];

                    for(var i in storeData.result.Stores){
                        if(storeData.result.Stores[i].IsOpen &&
                            storeData.result.Stores[i].IsOnlineNow &&
                            storeData.result.Stores[i].ServiceIsOpen.Delivery
                        ){
                            order.StoreID=storeData.result.Stores[i].StoreID;
                            break;
                        }
                    }

                    if(!order.StoreID){
                        console.log('No Open Stores allowing delivery right now for the specified location'.bgRed.black.bold);
                        throw('NO PIZZA FOR YOU! Look at a menu next time!');
                        return;
                    }
                }
            );

            validateOrder();
        }
    );
}

function findStores(address, closest, menu, fullMenu){
    if(!address){
        console.log('Need to know where to look, please provide atleast a zip code');
        rl.prompt();
        return;
    }
    console.log('Looking for stores near '+address.info+'...');
    rl.prompt();
    var nearAddress=new pizzapi.Address(process.env.ADDRESS);

    if(!nearAddress.PostalCode){
        console.log('Not a valid address'.red+' you must at least provide a zipcode');
        return;
    }
    pizzapi.Util.findNearbyStores(
        nearAddress,
        'Delivery',
        function(storeData){
            var openStores=[];

            order.Address=new pizzapi.Address(storeData.result.Address);

            for(var i in storeData.result.Stores){
                if(storeData.result.Stores[i].IsOpen &&
                    storeData.result.Stores[i].IsOnlineNow &&
                    storeData.result.Stores[i].ServiceIsOpen.Delivery
                ){
                    openStores.push(storeData.result.Stores[i]);
                }
            }

            if(openStores.length<1){
                console.log('No Open Stores allowing delivery right now for the specified location'.bgRed.black.bold);
                return;
            }

            var count=openStores.length;

            if(closest){
                count=1;
                order.StoreID=openStores[0].StoreID
            }
            console.log('\n');
            for(var i=0; i<count; i++){
                var store=openStores[i];

                console.log(
                    '###############################################################\n'.blue+
                    (
                        'StoreID : '+store.StoreID.bold+
                        '\nAddress : '+store.AddressDescription+
                        '\nPhone : '+store.Phone+
                        '\nDelivery Hours : '+store.ServiceHoursDescription.Delivery
                    ).store.white
                );
            }

            rl.prompt();

            if(!menu && !fullMenu)
                return;

            if(menu){
                showMenu(
                    openStores[0].StoreID,
                    true
                );
                rl.prompt();
                return;
            }

            if(fullMenu){
                showMenu(
                    openStores[0].StoreID
                );
                return;
            }
        }
    );
}

function orderPizza(items){
    var items=items.split(',');
    for(var i=0; i<items.length; i++){
        //create a new item to add to the order
        order.addItem(
            new pizzapi.Item(
                {
                    code: items[i].trim(),
                    options: [],
                    quantity: 1
                }
            )
        );
    }

    if(!order.Address.Street){
        rl.question(
            'what is the full address for delivery? ',
            validateAddress
        );
        return;
    }

    validateOrder();
}

function validateOrder(){
    //console.log('validating order');
    if(!order.FirstName){
        setTimeout(
            function(){
                rl.question(
                    'First Name? ',
                    function(data){
                        order.FirstName=data;
                        validateOrder();
                    }
                );
            },100
        );
        return;
    }

    if(!order.LastName){
        rl.question(
            'Last Name? ',
            function(data){
                order.LastName=data;
                validateOrder();
            }
        );
        return;
    }

    if(!order.Email){
        rl.question(
            'E-Mail? ',
            function(data){
                order.Email=data;
                validateOrder();
            }
        );
        return;
    }

    if(!order.Phone){
        rl.question(
            'Phone number? ',
            function(data){
                order.Phone=data;
                validateOrder();
            }
        );
        return;
    }

    order.validate(orderValidated);
}

function orderValidated(){
    order.price(pricedOrder);
}

function pricedOrder() {

    var cardInfo = new order.PaymentObject();
    cardInfo.Amount = order.Amounts.Customer;
    order.Payments.push(cardInfo);

    placeOrder();
}

function placeOrder(){
    if(!order.Payments[0].Number){
        rl.question(
            'Credit Card Number? ',
            function(data){
                order.Payments[0].Number = data;
                order.Payments[0].CardType = order.validateCC(data);
                placeOrder();
            }
        );
        return;
    }

    if(!order.Payments[0].Expiration){
        rl.question(
            'Credit Card Expiration? ',
            function(data){
                order.Payments[0].Expiration = data.replace(/\D/g,'');
                placeOrder();
            }
        );
        return;
    }

    if(!order.Payments[0].SecurityCode){
        rl.question(
            'Credit Card Security Code or CVV (3 or 4 digit code on card)? ',
            function(data){
                order.Payments[0].SecurityCode = data;
                placeOrder();
            }
        );
        return;
    }

    if(!order.Payments[0].PostalCode){
        rl.question(
            'Postal Code? ',
            function(data){
                order.Payments[0].PostalCode = data;
                placeOrder();
            }
        );
        rl.write(order.Address.PostalCode);
        return;
    }

    order.place(orderPlaced);
}

function orderPlaced(data){
    if(data.result.Order.Status==-1){
        console.log('You\'r order failed to process.');
        if(data.result.Order.StatusItems){
            for(var i in data.result.Order.StatusItems){
                console.log(data.result.Order.StatusItems[i]);
            }
        }
        console.log('Corrective Actions from Domino\'s Pizza : '+data.result.CorrectiveAction);

        rl.prompt();
        return;
    }

    trackOrder();
}

function trackOrder(){
    pizzapi.Track.orderKey(
        order.OrderID,
        order.StoreID,
        function(pizzaData){
            readline.cursorTo(process.stdout, 0, 0);
            readline.clearScreenDown(process.stdout);

            console.log(JSON.stringify(pizzaData.orders));
            setTimeout(
                trackOrder,
                15000
            );
        }
    );
}
<|endoftext|>


<commit_before>/*jslint plusplus: true, vars: true, nomen: true */
/*global define */

define(function (require, exports, module) {
    "use strict";

    var q = require("../thirdparty/q");

    function GitControl(options) {
        this._isHandlerRunning = false;
        this._queue = [];
        this.options = options || {};
    }

    GitControl.prototype = {

        _processQueue: function () {
            var self = this;
            if (self._isHandlerRunning || self._queue.length === 0) { return; }
            self._isHandlerRunning = true;

            var queueItem = self._queue.shift(),
                promise = queueItem[0],
                cmd = queueItem[1];

            self.options.executeHandler(cmd)
                .then(function (result) {
                    promise.resolve(result);
                    self._isHandlerRunning = false;
                    self._processQueue();
                })
                .fail(function (ex) {
                    promise.reject(ex);
                    self._isHandlerRunning = false;
                    self._processQueue();
                });
        },

        executeCommand: function (cmd) {
            var rv = q.defer();
            this._queue.push([rv, cmd]);
            this._processQueue();
            return rv.promise;
        },

        getVersion: function () {
            return this.executeCommand("git --version").then(function (output) {
                var io = output.indexOf("git version");
                return output.substring(io !== -1 ? io + "git version".length : 0).trim();
            }).fail(function (error) {
                // 'git' is not recognized as an internal or external command
                throw error;
            });
        },

        getRepositoryRoot: function () {
            return this.executeCommand("git rev-parse --show-toplevel").then(function (output) {
                // Git returns directory name without trailing slash
                return output.trim() + "/";
            }).fail(function (error) {
                // Not a git repository (or any of the parent directories): .git
                throw error;
            });
        },

        getBranchName: function () {
            return this.executeCommand("git rev-parse --abbrev-ref HEAD");
        },

        getGitStatus: function () {
            return this.executeCommand("git status --porcelain").then(function (stdout) {
                if (stdout.length === 0) { return []; }

                var results = [],
                    lines = stdout.split("\n");
                lines.forEach(function (line) {
                    var status = line.substring(0, 2),
                        file = line.substring(3);

                    switch (status) {
                    case "A ":
                        status = "STAGED;NEWFILE";
                        break;
                    case " D":
                        status = "DELETED";
                        break;
                    case "M ":
                        status = "STAGED";
                        break;
                    case " M":
                        status = "MODIFIED";
                        break;
                    case "MM":
                        status = "STAGED;MODIFIED";
                        break;
                    case "??":
                        status = "UNTRACKED";
                        break;
                    default:
                        throw new Error("Unexpected status: " + status);
                    }

                    results.push({
                        status: status,
                        file: file
                    });
                });
                return results.sort(function (a, b) {
                    if (a.file < b.file) { return -1; }
                    if (a.file > b.file) { return 1; }
                    return 0;
                });
            });
        },

        gitAdd: function (file, updateIndex) {
            var cmd = "git add ";
            if (updateIndex) { cmd += "-u "; }
            cmd += "\"" + file + "\"";
            return this.executeCommand(cmd);
        },

        gitCommit: function (message) {
            return this.executeCommand("git commit -m \"" + message + "\"");
        },

        gitReset: function () {
            return this.executeCommand("git reset");
        },

        gitDiff: function (file) {
            return this.executeCommand("git diff -U0 \"" + file + "\"");
        }

    };

    module.exports = GitControl;
});<commit_msg>externalised git to a variable<commit_after>/*jslint plusplus: true, vars: true, nomen: true */
/*global define */

define(function (require, exports, module) {
    "use strict";

    var q = require("../thirdparty/q");
    //var git ='"C:\\Program Files (x86)\\Git\\bin\\git.exe"';
    var git = "git";

    function GitControl(options) {
        this._isHandlerRunning = false;
        this._queue = [];
        this.options = options || {};
    }

    GitControl.prototype = {

        _processQueue: function () {
            var self = this;
            if (self._isHandlerRunning || self._queue.length === 0) { return; }
            self._isHandlerRunning = true;

            var queueItem = self._queue.shift(),
                promise = queueItem[0],
                cmd = queueItem[1];

            self.options.executeHandler(cmd)
                .then(function (result) {
                    promise.resolve(result);
                    self._isHandlerRunning = false;
                    self._processQueue();
                })
                .fail(function (ex) {
                    promise.reject(ex);
                    self._isHandlerRunning = false;
                    self._processQueue();
                });
        },

        executeCommand: function (cmd) {
            var rv = q.defer();
            this._queue.push([rv, cmd]);
            this._processQueue();
            return rv.promise;
        },

        getVersion: function () {
            return this.executeCommand(git+" --version").then(function (output) {
                var io = output.indexOf(git+" version");
                return output.substring(io !== -1 ? io + git+" version".length : 0).trim();
            }).fail(function (error) {
                // 'git' is not recognized as an internal or external command
                throw error;
            });
        },

        getRepositoryRoot: function () {
            return this.executeCommand(git+" rev-parse --show-toplevel").then(function (output) {
                // Git returns directory name without trailing slash
                return output.trim() + "/";
            }).fail(function (error) {
                // Not a git repository (or any of the parent directories): .git
                throw error;
            });
        },

        getBranchName: function () {
            return this.executeCommand(git+" rev-parse --abbrev-ref HEAD");
        },

        getGitStatus: function () {
            return this.executeCommand(git+" status --porcelain").then(function (stdout) {
                if (stdout.length === 0) { return []; }

                var results = [],
                    lines = stdout.split("\n");
                lines.forEach(function (line) {
                    var status = line.substring(0, 2),
                        file = line.substring(3);

                    switch (status) {
                    case "A ":
                        status = "STAGED;NEWFILE";
                        break;
                    case " D":
                        status = "DELETED";
                        break;
                    case "M ":
                        status = "STAGED";
                        break;
                    case " M":
                        status = "MODIFIED";
                        break;
                    case "MM":
                        status = "STAGED;MODIFIED";
                        break;
                    case "??":
                        status = "UNTRACKED";
                        break;
                    default:
                        throw new Error("Unexpected status: " + status);
                    }

                    results.push({
                        status: status,
                        file: file
                    });
                });
                return results.sort(function (a, b) {
                    if (a.file < b.file) { return -1; }
                    if (a.file > b.file) { return 1; }
                    return 0;
                });
            });
        },

        gitAdd: function (file, updateIndex) {
            var cmd = git+" add ";
            if (updateIndex) { cmd += "-u "; }
            cmd += "\"" + file + "\"";
            return this.executeCommand(cmd);
        },

        gitCommit: function (message) {
            return this.executeCommand(git+" commit -m \"" + message + "\"");
        },

        gitReset: function () {
            return this.executeCommand(git+" reset");
        },

        gitDiff: function (file) {
            return this.executeCommand(git+" diff -U0 \"" + file + "\"");
        }

    };

    module.exports = GitControl;
});
<|endoftext|>


<commit_before>app.get('/webhook', function(req, res) {
  if (req.query['hub.mode'] === 'subscribe' &&
      req.query['hub.verify_token'] === <sivansivan>) {
    console.log("Validating webhook");
    res.status(200).send(req.query['hub.challenge']);
  } else {
    console.error("Failed validation. Make sure the validation tokens match.");
    res.sendStatus(403);
  }
});
<commit_msg>token r5<commit_after>app.get('/webhook/', function (req, res) {
  if (req.query['hub.verify_token'] === 'sivansivan') {
    res.send(req.query['hub.challenge']);
  }
  res.send('Error, wrong validation token');
})
<|endoftext|>