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

var express = require('express');
var MongoStore = require('connect-mongo')(express);
var flash = require('express-flash');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var expressValidator = require('express-validator');
var SummaryTool = require('node-summary');
var AWS = require('aws-sdk')
var nodecr = require('nodecr')
var exec = require('child_process').execFile;
var config = new AWS.Config({accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, region: 'us-west-2'})
var s3 = new AWS.S3({accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, region: 'us-west-2'});

/**
 * Load controllers.
 */

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

/**
 * API keys + Passport configuration.
 */

var secrets = require('./config/secrets');
var passportConf = require('./config/passport');

/**
 * Create Express server.
 */

var app = express();

/**
 * Mongoose configuration.
 */

mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
  console.error('✗ MongoDB Connection Error. Please make sure MongoDB is running.');
});

/**
 * Express configuration.
 */

var hour = 3600000;
var day = (hour * 24);
var week = (day * 7);
var month = (day * 30);

app.engine('jade', require('jade').renderFile);
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(require('connect-assets')({
  src: 'public',
  helperContext: app.locals
}));
app.use(express.compress());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.json());
app.use(express.urlencoded());
app.use(expressValidator());
app.use(express.methodOverride());
app.use(express.session({
  secret: secrets.sessionSecret

}));
// app.use(express.csrf());
app.use(passport.initialize());
app.use(passport.session());
/*app.use(function(req, res, next) {
  res.locals.user = req.user;
  res.locals.token = req.csrfToken();
  res.locals.secrets = secrets;
  next();
});
*/
app.use(flash());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public'), { maxAge: week }));
app.use(function(req, res) {
  res.status(404);
  res.render('404');
});
app.use(express.errorHandler());

var summarize = function(title, content, callback){
  SummaryTool.summarize(title, content, function(err, summary) {
    if(err) console.log("Something went wrong man!");

    console.log(summary);

    console.log("Original Length " + (title.length + content.length));
    console.log("Summary Length " + summary.length);
    console.log("Summary Ratio: " + (100 - (100 * (summary.length / (title.length + content.length)))));
    callback(summary);
  });
}
/**
 * Application routes.
 */
app.get('/', function(req, res){
  res.render("home");
});

app.get("/test", function(req, res){
  var title = "Swayy is a beautiful new dashboard for discovering and curating online content [Invites]";
  var content = "";
  content += "Lior Degani, the Co-Founder and head of Marketing of Swayy, pinged me last week when I was in California to tell me about his startup and give me beta access. I heard his pitch and was skeptical. I was also tired, cranky and missing my kids – so my frame of mind wasn't the most positive.\n";
  content += "I went into Swayy to check it out, and when it asked for access to my Twitter and permission to tweet from my account, all I could think was, \"If this thing spams my Twitter account I am going to bitch-slap him all over the Internet.\" Fortunately that thought stayed in my head, and not out of my mouth.\n";
  content += "One week later, I'm totally addicted to Swayy and glad I said nothing about the spam (it doesn't send out spam tweets but I liked the line too much to not use it for this article). I pinged Lior on Facebook with a request for a beta access code for TNW readers. I also asked how soon can I write about it. It's that good. Seriously. I use every content curation service online. It really is That Good.\n";
  content += "What is Swayy? It's like Percolate and LinkedIn recommended articles, mixed with trending keywords for the topics you find interesting, combined with an analytics dashboard that shows the trends of what you do and how people react to it. I like it for the simplicity and accuracy of the content curation.\n";
  content += "Everything I'm actually interested in reading is in one place – I don't have to skip from another major tech blog over to Harvard Business Review then hop over to another major tech or business blog. It's all in there. And it has saved me So Much Time\n\n";
  content += "After I decided that I trusted the service, I added my Facebook and LinkedIn accounts. The content just got That Much Better. I can share from the service itself, but I generally prefer reading the actual post first – so I end up sharing it from the main link, using Swayy more as a service for discovery.\n";
  content += "I'm also finding myself checking out trending keywords more often (more often than never, which is how often I do it on Twitter.com).\n\n\n";
  content += "The analytics side isn't as interesting for me right now, but that could be due to the fact that I've barely been online since I came back from the US last weekend. The graphs also haven't given me any particularly special insights as I can't see which post got the actual feedback on the graph side (however there are numbers on the Timeline side.) This is a Beta though, and new features are being added and improved daily. I'm sure this is on the list. As they say, if you aren't launching with something you're embarrassed by, you've waited too long to launch.\n";
  content += "It was the suggested content that impressed me the most. The articles really are spot on – which is why I pinged Lior again to ask a few questions:\n";
  content += "How do you choose the articles listed on the site? Is there an algorithm involved? And is there any IP?\n";
  content += "Yes, we're in the process of filing a patent for it. But basically the system works with a Natural Language Processing Engine. Actually, there are several parts for the content matching, but besides analyzing what topics the articles are talking about, we have machine learning algorithms that match you to the relevant suggested stuff. For example, if you shared an article about Zuck that got a good reaction from your followers, we might offer you another one about Kevin Systrom (just a simple example).\n";
  content += "Who came up with the idea for Swayy, and why? And what's your business model?\n";
  content += "Our business model is a subscription model for extra social accounts (extra Facebook / Twitter, etc) and team collaboration.\n";
  content += "The idea was born from our day-to-day need to be active on social media, look for the best content to share with our followers, grow them, and measure what content works best.\n";
  content += "Who is on the team?\n";
  content += "Ohad Frankfurt is the CEO, Shlomi Babluki is the CTO and Oz Katz does Product and Engineering, and I [Lior Degani] do Marketing. The four of us are the founders. Oz and I were in 8200 [an elite Israeli army unit] together. Emily Engelson does Community Management and Graphic Design.\n";
  content += "If you use Percolate or read LinkedIn's recommended posts I think you'll love Swayy.\n";
  content += "Want to try Swayy out without having to wait? Go to this secret URL and enter the promotion code thenextweb . The first 300 people to use the code will get access.\n";
  content += "Image credit: Thinkstock";
  summarize(title, content, function(summary){
    res.render("test", {
      summary : summary
    }
      );
  });

});

/*
/*

/*
Function to process files. Gets file object from AWS, runs OCR on it,
resaves as processed file
*/
var process_file = function(file){
 var args = [file];
 exec('JavaCode.exe', args, null, function(err, data) {
        console.log(err)
        console.log(data.toString());
    });

}

/*
Gets a file and returns a URL pointing to the file to the requester
*/
app.get('/file', function(req, res){
  var filename = req.query.filename;
  console.log(filename);
  var params = {Bucket : 'cloudnotes2014', Key: filename};
  var signed_url = s3.getSignedUrl('getObject', params);
  res.json({url : signed_url});
});

app.post('/file', function(req, res){
/*  var url = req.body.url;

  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", url, false );
  xmlHttp.send( null );

  var file_data = xmlHttp.responseText;
  var filename = "test android post";

  var params = {Bucket: 'cloudnotes2014', Key: filename, Body: file_data};
  s3.putObject(params, function(err, data){
    console.log(err);

  });
*/
  console.log(req.body);
  console.log(req.files);
  //console.log(req);
  var file_data = req.files.picture_data;
  var filename = req.body.timestamp;

  var params = {Bucket: 'cloudnotes2014', Key: filename, Body: file_data};
  s3.putObject(params, function(err, data){
    console.log(err);

  });
});

app.get('/file_post', function(req, res){
  var file_data = req.params.picture_data;
  console.log(req.body);
  console.log(req.params);
  console.log(req);
  //console.log(req);
  var filename = "test android post";
  console.log("file_data: "+file_data+" filename: "+filename);
  var params = {Bucket: 'cloudnotes2014', Key: filename, Body: file_data};
  s3.putObject(params, function(err, data){
    console.log(err);

  });
});

/**
 * OAuth routes for sign-in.
 */

/**
 * Start Express server.
 */

app.listen(app.get('port'), function() {
  console.log("✔ Express server listening on port %d in %s mode", app.get('port'), app.settings.env);
});
<commit_msg>modified with AWS REST post from android<commit_after>/**
 * Module dependencies.
 */

var express = require('express');
var MongoStore = require('connect-mongo')(express);
var flash = require('express-flash');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var expressValidator = require('express-validator');
var SummaryTool = require('node-summary');
var AWS = require('aws-sdk')
var nodecr = require('nodecr')
var exec = require('child_process').execFile;
var config = new AWS.Config({accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, region: 'us-west-2'})
var s3 = new AWS.S3({accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, region: 'us-west-2'});

/**
 * Load controllers.
 */

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

/**
 * API keys + Passport configuration.
 */

var secrets = require('./config/secrets');
var passportConf = require('./config/passport');

/**
 * Create Express server.
 */

var app = express();

/**
 * Mongoose configuration.
 */

mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
  console.error('✗ MongoDB Connection Error. Please make sure MongoDB is running.');
});

/**
 * Express configuration.
 */

var hour = 3600000;
var day = (hour * 24);
var week = (day * 7);
var month = (day * 30);

app.engine('jade', require('jade').renderFile);
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(require('connect-assets')({
  src: 'public',
  helperContext: app.locals
}));
app.use(express.compress());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.json());
app.use(express.urlencoded());
app.use(expressValidator());
app.use(express.methodOverride());
app.use(express.session({
  secret: secrets.sessionSecret

}));
// app.use(express.csrf());
app.use(passport.initialize());
app.use(passport.session());
/*app.use(function(req, res, next) {
  res.locals.user = req.user;
  res.locals.token = req.csrfToken();
  res.locals.secrets = secrets;
  next();
});
*/
app.use(flash());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public'), { maxAge: week }));
app.use(function(req, res) {
  res.status(404);
  res.render('404');
});
app.use(express.errorHandler());

var summarize = function(title, content, callback){
  SummaryTool.summarize(title, content, function(err, summary) {
    if(err) console.log("Something went wrong man!");

    console.log(summary);

    console.log("Original Length " + (title.length + content.length));
    console.log("Summary Length " + summary.length);
    console.log("Summary Ratio: " + (100 - (100 * (summary.length / (title.length + content.length)))));
    callback(summary);
  });
}
/**
 * Application routes.
 */
app.get('/', function(req, res){
  res.render("home");
});

app.get("/test", function(req, res){
  var title = "Swayy is a beautiful new dashboard for discovering and curating online content [Invites]";
  var content = "";
  content += "Lior Degani, the Co-Founder and head of Marketing of Swayy, pinged me last week when I was in California to tell me about his startup and give me beta access. I heard his pitch and was skeptical. I was also tired, cranky and missing my kids – so my frame of mind wasn't the most positive.\n";
  content += "I went into Swayy to check it out, and when it asked for access to my Twitter and permission to tweet from my account, all I could think was, \"If this thing spams my Twitter account I am going to bitch-slap him all over the Internet.\" Fortunately that thought stayed in my head, and not out of my mouth.\n";
  content += "One week later, I'm totally addicted to Swayy and glad I said nothing about the spam (it doesn't send out spam tweets but I liked the line too much to not use it for this article). I pinged Lior on Facebook with a request for a beta access code for TNW readers. I also asked how soon can I write about it. It's that good. Seriously. I use every content curation service online. It really is That Good.\n";
  content += "What is Swayy? It's like Percolate and LinkedIn recommended articles, mixed with trending keywords for the topics you find interesting, combined with an analytics dashboard that shows the trends of what you do and how people react to it. I like it for the simplicity and accuracy of the content curation.\n";
  content += "Everything I'm actually interested in reading is in one place – I don't have to skip from another major tech blog over to Harvard Business Review then hop over to another major tech or business blog. It's all in there. And it has saved me So Much Time\n\n";
  content += "After I decided that I trusted the service, I added my Facebook and LinkedIn accounts. The content just got That Much Better. I can share from the service itself, but I generally prefer reading the actual post first – so I end up sharing it from the main link, using Swayy more as a service for discovery.\n";
  content += "I'm also finding myself checking out trending keywords more often (more often than never, which is how often I do it on Twitter.com).\n\n\n";
  content += "The analytics side isn't as interesting for me right now, but that could be due to the fact that I've barely been online since I came back from the US last weekend. The graphs also haven't given me any particularly special insights as I can't see which post got the actual feedback on the graph side (however there are numbers on the Timeline side.) This is a Beta though, and new features are being added and improved daily. I'm sure this is on the list. As they say, if you aren't launching with something you're embarrassed by, you've waited too long to launch.\n";
  content += "It was the suggested content that impressed me the most. The articles really are spot on – which is why I pinged Lior again to ask a few questions:\n";
  content += "How do you choose the articles listed on the site? Is there an algorithm involved? And is there any IP?\n";
  content += "Yes, we're in the process of filing a patent for it. But basically the system works with a Natural Language Processing Engine. Actually, there are several parts for the content matching, but besides analyzing what topics the articles are talking about, we have machine learning algorithms that match you to the relevant suggested stuff. For example, if you shared an article about Zuck that got a good reaction from your followers, we might offer you another one about Kevin Systrom (just a simple example).\n";
  content += "Who came up with the idea for Swayy, and why? And what's your business model?\n";
  content += "Our business model is a subscription model for extra social accounts (extra Facebook / Twitter, etc) and team collaboration.\n";
  content += "The idea was born from our day-to-day need to be active on social media, look for the best content to share with our followers, grow them, and measure what content works best.\n";
  content += "Who is on the team?\n";
  content += "Ohad Frankfurt is the CEO, Shlomi Babluki is the CTO and Oz Katz does Product and Engineering, and I [Lior Degani] do Marketing. The four of us are the founders. Oz and I were in 8200 [an elite Israeli army unit] together. Emily Engelson does Community Management and Graphic Design.\n";
  content += "If you use Percolate or read LinkedIn's recommended posts I think you'll love Swayy.\n";
  content += "Want to try Swayy out without having to wait? Go to this secret URL and enter the promotion code thenextweb . The first 300 people to use the code will get access.\n";
  content += "Image credit: Thinkstock";
  summarize(title, content, function(summary){
    res.render("test", {
      summary : summary
    }
      );
  });

});

/*
/*

/*
Function to process files. Gets file object from AWS, runs OCR on it,
resaves as processed file
*/
var process_file = function(file){
 var args = [file];
 exec('JavaCode.exe', args, null, function(err, data) {
        console.log(err)
        console.log(data.toString());
    });

}

/*
Gets a file and returns a URL pointing to the file to the requester
*/
app.get('/file', function(req, res){
  var filename = req.query.filename;
  console.log(filename);
  var params = {Bucket : 'cloudnotes2014', Key: filename};
  var signed_url = s3.getSignedUrl('getObject', params);
  res.json({url : signed_url});
});

app.post('/file', function(req, res){
/*  var url = req.body.url;

  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", url, false );
  xmlHttp.send( null );

  var file_data = xmlHttp.responseText;
  var filename = "test android post";

  var params = {Bucket: 'cloudnotes2014', Key: filename, Body: file_data};
  s3.putObject(params, function(err, data){
    console.log(err);

  });
*/
  console.log(req.body);
  //console.log(req.files);
  //console.log(req);
  var file_data = req.files.picture_data;
  var filename = req.body.file_name;

  var params = {Bucket: 'cloudnotes2014', Key: filename};
  var obj = s3.getObject(params, function(err, data){
    console.log(err);
    console.log(data.body.slice(0, 10));

  });
});

app.get('/file_post', function(req, res){
  var file_data = req.params.picture_data;
  console.log(req.body);
  console.log(req.params);
  console.log(req);
  //console.log(req);
  var filename = "test android post";
  console.log("file_data: "+file_data+" filename: "+filename);
  var params = {Bucket: 'cloudnotes2014', Key: filename, Body: file_data};
  s3.putObject(params, function(err, data){
    console.log(err);

  });
});

/**
 * OAuth routes for sign-in.
 */

/**
 * Start Express server.
 */

app.listen(app.get('port'), function() {
  console.log("✔ Express server listening on port %d in %s mode", app.get('port'), app.settings.env);
});
<|endoftext|>


<commit_before>var koa = require('koa');
var app = module.exports = koa();

app.use(function *(){
  this.body = 'Jason, You\'re an Idiot \n';
});

if (!module.parent) app.listen(8080);

  console.log('Started Server');
<commit_msg>changed msg<commit_after>var koa = require('koa');
var app = module.exports = koa();

app.use(function *(){
  this.body = 'Hello World \n';
});

if (!module.parent) app.listen(8080);

  console.log('Started Server');
<|endoftext|>


<commit_before>'use strict';

var canvas = document.getElementById('stage'),
  ctx = canvas.getContext('2d');

//HANGMAN DRAWING DOWN BELOW:
function drawLine(ctx , from, to) {
  ctx.beginPath();
  ctx.moveTo(from[0], from[1]);
  ctx.lineTo(to[0], to[1]);
  ctx.stroke();
}
drawLine(ctx, [0,0], [100,50]);
function drawCanvas() {
  canvas.width = canvas.width; //resetting the canvas everytime
  ctx.lineWidth = 10; //setting the basic styles
  ctx.strokeStyle = 'black'; //setting the basic styles
  ctx.fillStyle = 'black'; //setting the basic styles
  drawLine(ctx, [20,190], [180,190]); //draws the ground
  if (incorrectGuesses >= 1) { //creates the upright gallows:
    ctx.strokeStyle = 'black';
    drawLine(ctx, [30,185], [30,10]);
  }
  if (incorrectGuesses >= 1) { //creates the arm gallows:
    ctx.lineTo(150,10);
    ctx.stroke();
  }
  if (incorrectGuesses >= 2) { //creates the noose:
    ctx.strokeStyle = 'black';
    ctx.lineWidth = 3;
    drawLine(ctx, [145,15], [145,30]);

    ctx.beginPath(); //creates the head:
    ctx.moveTo(160, 45);
    ctx.arc(145, 45, 15, 0, (Math.PI / 180) * 360);
    ctx.stroke();
  }
  if (incorrectGuesses >= 3) { //creates the body:
    drawLine(ctx, [145,60], [145,130]);
  }
  if (incorrectGuesses >= 4) { //creates the left arm:
    drawLine(ctx, [145,80], [110,90]);
  }
  if (incorrectGuesses >= 5) { //creates the right arm:
    drawLine(ctx, [145,80], [180,90]);
  }
  if (incorrectGuesses >= 6) { //creates the left leg:
    drawLine(ctx, [145,130], [130,170]);
  }
  if (incorrectGuesses >= 7) { //creates the right leg and ends game
    drawLine(ctx, [145,130], [160,170]);
  }
}
//HANGMAN DRAWING UP ABOVE

// Global variables
var playerAnswerArr = []; // blank spaces puzzle
var incorrectGuesses = 0;
var maxEasyGuesses = 7; // will correspond with number of easy difficulty body parts
var easyWords = ['four', 'phone', 'mouse', 'bottle', 'notebook']; // subject to change
var gameWord; // word chosen from word array
var remainingLetters; // remaining letters left to guess in the gameWord
var wonGame = false; // used in checkForWin/Loss and updatePlayerStats
var letterButton = document.getElementById('letter_buttons');
letterButton.addEventListener('click', handleClick); // listens for a button click
var display = document.getElementById('display_player_array');
var playAgainButton = document.getElementById('play_again_btn');
playAgainButton.addEventListener('click', handlePlayAgain);
var endMessage = document.getElementById('end_of_game_msg');
//JSON VARIABLES
var localStorageNameArr = localStorage.getItem('allPlayerNames');
var localStorageObjArr  = localStorage.getItem('players');
var parsedLclStrgNameArr = JSON.parse(localStorageNameArr);   // get the name array from local storage and parse from JSON to js
var parsedlclStrgObjArr  = JSON.parse(localStorageObjArr);   // get the player object array from local storage and parse from JSON to js
var currentPlayer = parsedlclStrgObjArr[0];

retrieveLocal();
findCurrentPlayer();
renderPlayerStatsRow(currentPlayer);

// - generate a hanging man
// _______ADDRESS______________________

// FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS //
//retrieve local storage
function retrieveLocal() {
  if (localStorageNameArr) {
    parsedLclStrgNameArr = JSON.parse(localStorageNameArr);
    parsedlclStrgObjArr = JSON.parse(localStorageObjArr);
  }
};

// find current player
function findCurrentPlayer() {
  var playerToCheck = parsedLclStrgNameArr.pop(); // pop off the last element (the current logged in user) and store it on a variable
  for (var i = 0; i < parsedlclStrgObjArr.length; i++) {  // compare the playerToCheck to the player names in the object array
    if (playerToCheck === parsedlclStrgObjArr[i].playerName) {// if there's a name match, update other object properties
      currentPlayer = parsedlclStrgObjArr[i];
    }
  }
};

// handles the event when 'play again' button is clicked
function handlePlayAgain(event) {
  // reloads the page and starts it at the top
  window.location.reload();
  window.onbeforeunload = function () {
    window.scrollTo(0, 0);
  };
}

// handles the event of a letter button click
function handleClick(event) {
  event.preventDefault(); // prevent page refresh

  // determine if the event.target.value is in the gameWord array
  if (gameWord.includes(event.target.value) === true) {
    // loop through the gameWord to match target value (letter) with any same letter in the gameword
    for (var i = 0; i < gameWord.length; i++) {
      if (event.target.value === gameWord[i]) {

        playerAnswerArr[i] = gameWord[i]; // replace the blank index with the matching letter

        displayPlayerArray(playerAnswerArr); // update the display for the player
        remainingLetters--;
        // disable the button to prevent the player from selecting it again
        event.target.disabled = true;
        checkForWin();
      }
    }
  } else if (gameWord.includes(event.target.value) === false) {
    // if user selects a invalid letter, nothing changes in the playerAnswerArr
    displayPlayerArray(playerAnswerArr);

    //       - one body part gets added to the hangman

    incorrectGuesses += 1; // incorrectGuesses increases by 1
    // disable the button to prevent the player from selecting it again
    event.target.disabled = true;
    checkForLoss();
  }
  drawCanvas();
}

function checkForWin() {
  if (remainingLetters === 0) { // if the player has guessed all the letters
    wonGame = true;
    // disable the buttons, display the solved gameWord, inform the player that they won, and updatePlayerStats
    letterButton.removeEventListener('click', handleClick);
    displayPlayerArray(playerAnswerArr);
    endMessage.textContent = 'Congrats! You won and saved the hangman!';
    updatePlayerStats();
    //   - refresh page?
  }
}

function checkForLoss() {
  if (remainingLetters > 0 && incorrectGuesses === maxEasyGuesses) {
    wonGame = false;
    //   - hangman will have all parts
    drawCanvas();
    //   - display correct letters in the puzzle as the answer

    // disable the buttons, inform the player that they lost, and updatePlayerStats
    letterButton.removeEventListener('click', handleClick);
    endMessage.textContent = 'You failed to guess \'' + gameWord + '.\' A man has been hanged today. You lose.';
    updatePlayerStats();
    //   - refresh page?
  }
}

function updatePlayerStats() {
  currentPlayer.gamesPlayed ++;
  if (wonGame === true) {
    currentPlayer.totalPoints += 23; ////////THIS WILL PROBABLY CHANGE///////////////
    currentPlayer.gamesWon ++;
  }
  var numberWon = Math.round((currentPlayer.gamesWon / currentPlayer.gamesPlayed) * 100);
  currentPlayer.percentWon = numberWon;
  currentPlayer.percentDisplay = numberWon + '%';
  clearRow();
  sortPlayers();
  setRank();
  renderPlayerStatsRow(currentPlayer);
  // stringify the updated array and set it back to local storage
  storeLocal();
};

function sortPlayers(){
  parsedlclStrgObjArr.sort(function(a, b) {
    if (a.totalPoints === b.totalPoints) {
      return (b.percentWon) - (a.percentWon);
    } else {
      return (b.totalPoints) - (a.totalPoints);
    }
  });
};

function setRank(){
  clearRow();
  var rank = 0;
  var playersLength = parsedlclStrgObjArr.length;
  if (playersLength > 5) {
    playersLength = 5;
  }
  for (var i = 0; i < playersLength; i++) {
    rank = rank + 1;
    parsedlclStrgObjArr[i].ranking = rank;
  }
};

function storeLocal() {
  var playersJSON = JSON.stringify(parsedlclStrgObjArr);
  localStorage.setItem('players', playersJSON);
};

// pass in a word array to select a random word from it to assign to gameWord
function pickWord (wordArr) {
  gameWord = wordArr[generateRandomNumber(wordArr)];
  return gameWord;

  function generateRandomNumber(arr) {
    return Math.floor(Math.random() * arr.length);
  }
}

// initiate the playerAnswerArr to '_' characters, the length of the gameWord
function generatePlayerAnswerArray (gameWord) {
  for (var i = 0; i < gameWord.length; i++) {
    playerAnswerArr.push('_');
  };
}

// display the playerAnswerArr in html
function displayPlayerArray(playerAnswerArr) {
  display.textContent = playerAnswerArr.join(' ');
}

function runGame(){
  playerAnswerArr = [];
  // letterButton.addEventListener('click', handleClick); // listens for a button click
  // letterButton.disabled = false;
  // assign the gameWord
  gameWord = pickWord(easyWords);
  // set the remainingLetters left to guess
  remainingLetters = gameWord.length;
  // generate a playerAnswerArr blank puzzle that is the length of the gameWord and display it
  generatePlayerAnswerArray(gameWord);
  displayPlayerArray(playerAnswerArr);
}

//*****EXECUTE CODE*******************EXECUTE CODE**********************
runGame();

function renderPlayerStatsRow(currentPlayer) {

  var playerStatsTable = document.getElementById('stats_table_body');
  var playerTableRow = document.createElement('tr');
  var rankingPlayer = document.createElement('td');
  var playerNamePlayer = document.createElement('td');
  var gamesPlayedPlayer = document.createElement('td');
  var gamesWonPlayer = document.createElement('td');
  var percentageWonPlayer = document.createElement('td');
  var totalPointsPlayer = document.createElement('td');

  playerTableRow.appendChild(rankingPlayer);

  playerNamePlayer.textContent = currentPlayer.playerName;
  playerTableRow.appendChild(playerNamePlayer);

  gamesPlayedPlayer.textContent = currentPlayer.gamesPlayed;
  playerTableRow.appendChild(gamesPlayedPlayer);

  gamesWonPlayer.textContent = currentPlayer.gamesWon;
  playerTableRow.appendChild(gamesWonPlayer);

  percentageWonPlayer.textContent = currentPlayer.percentDisplay;
  playerTableRow.appendChild(percentageWonPlayer);

  totalPointsPlayer.textContent = currentPlayer.totalPoints;
  playerTableRow.appendChild(totalPointsPlayer);

  if (currentPlayer.ranking <= 5) {
    rankingPlayer.textContent = currentPlayer.ranking;
  } else {
    rankingPlayer.textContent = 'Not Ranked';
  }
  playerStatsTable.appendChild(playerTableRow);
};

function clearRow() {
  var playerStatsTable = document.getElementById('stats_table_body');
  playerStatsTable.textContent = '';
}

// function clearTable(){
//   var playerStatsTable = document.getElementById('stats_table_body');
//   playerStatsTable.textContent = '';
// };
<commit_msg>fixed merge conflict<commit_after>'use strict';

var canvas = document.getElementById('stage'),
  ctx = canvas.getContext('2d');

//HANGMAN DRAWING DOWN BELOW:
function drawLine(ctx , from, to) {
  ctx.beginPath();
  ctx.moveTo(from[0], from[1]);
  ctx.lineTo(to[0], to[1]);
  ctx.scale(2,2);
  ctx.stroke();
}
drawLine(ctx, [0,0], [100,50]);
function drawCanvas() {
  canvas.width = canvas.width; //resetting the canvas everytime
  ctx.lineWidth = 10; //setting the basic styles
  ctx.strokeStyle = 'black'; //setting the basic styles
  ctx.fillStyle = 'black'; //setting the basic styles
  drawLine(ctx, [20,190], [180,190]); //draws the ground
  if (incorrectGuesses >= 1) { //creates the upright gallows:
    ctx.strokeStyle = 'black';
    drawLine(ctx, [30,185], [30,10]);
  }
  if (incorrectGuesses >= 1) { //creates the arm gallows:
    ctx.lineTo(150,10);
    ctx.stroke();
  }
  if (incorrectGuesses >= 2) { //creates the noose:
    ctx.strokeStyle = 'black';
    ctx.lineWidth = 3;
    drawLine(ctx, [145,15], [145,30]);

    ctx.beginPath(); //creates the head:
    ctx.moveTo(160, 45);
    ctx.arc(145, 45, 15, 0, (Math.PI / 180) * 360);
    ctx.stroke();
  }
  if (incorrectGuesses >= 3) { //creates the body:
    drawLine(ctx, [145,60], [145,130]);
  }
  if (incorrectGuesses >= 4) { //creates the left arm:
    drawLine(ctx, [145,80], [110,90]);
  }
  if (incorrectGuesses >= 5) { //creates the right arm:
    drawLine(ctx, [145,80], [180,90]);
  }
  if (incorrectGuesses >= 6) { //creates the left leg:
    drawLine(ctx, [145,130], [130,170]);
  }
  if (incorrectGuesses >= 7) { //creates the right leg and ends game
    drawLine(ctx, [145,130], [160,170]);
  }
}
//HANGMAN DRAWING UP ABOVE

// Global variables
var playerAnswerArr = []; // blank spaces puzzle
var incorrectGuesses = 0;
var maxEasyGuesses = 7; // will correspond with number of easy difficulty body parts
var easyWords = ['four', 'phone', 'mouse', 'bottle', 'notebook']; // subject to change
var gameWord; // word chosen from word array
var remainingLetters; // remaining letters left to guess in the gameWord
var wonGame = false; // used in checkForWin/Loss and updatePlayerStats
var letterButton = document.getElementById('letter_buttons');
letterButton.addEventListener('click', handleClick); // listens for a button click
var display = document.getElementById('display_player_array');
var playAgainButton = document.getElementById('play_again_btn');
playAgainButton.addEventListener('click', handlePlayAgain);
var endMessage = document.getElementById('end_of_game_msg');
//JSON VARIABLES
var localStorageNameArr = localStorage.getItem('allPlayerNames');
var localStorageObjArr  = localStorage.getItem('players');
var parsedLclStrgNameArr = JSON.parse(localStorageNameArr);   // get the name array from local storage and parse from JSON to js
var parsedlclStrgObjArr  = JSON.parse(localStorageObjArr);   // get the player object array from local storage and parse from JSON to js
var currentPlayer = parsedlclStrgObjArr[0];

retrieveLocal();
findCurrentPlayer();
renderPlayerStatsRow(currentPlayer);

// - generate a hanging man
// _______ADDRESS______________________

// FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS // FUNCTIONS //
//retrieve local storage
function retrieveLocal() {
  if (localStorageNameArr) {
    parsedLclStrgNameArr = JSON.parse(localStorageNameArr);
    parsedlclStrgObjArr = JSON.parse(localStorageObjArr);
  }
};

// find current player
function findCurrentPlayer() {
  var playerToCheck = parsedLclStrgNameArr.pop(); // pop off the last element (the current logged in user) and store it on a variable
  for (var i = 0; i < parsedlclStrgObjArr.length; i++) {  // compare the playerToCheck to the player names in the object array
    if (playerToCheck === parsedlclStrgObjArr[i].playerName) {// if there's a name match, update other object properties
      currentPlayer = parsedlclStrgObjArr[i];
    }
  }
};

// handles the event when 'play again' button is clicked
function handlePlayAgain(event) {
  // reloads the page and starts it at the top
  window.location.reload();
  window.onbeforeunload = function () {
    window.scrollTo(0, 0);
  };
}

// handles the event of a letter button click
function handleClick(event) {
  event.preventDefault(); // prevent page refresh

  // determine if the event.target.value is in the gameWord array
  if (gameWord.includes(event.target.value) === true) {
    // loop through the gameWord to match target value (letter) with any same letter in the gameword
    for (var i = 0; i < gameWord.length; i++) {
      if (event.target.value === gameWord[i]) {

        playerAnswerArr[i] = gameWord[i]; // replace the blank index with the matching letter

        displayPlayerArray(playerAnswerArr); // update the display for the player
        remainingLetters--;
        // disable the button to prevent the player from selecting it again
        event.target.disabled = true;
        checkForWin();
      }
    }
  } else if (gameWord.includes(event.target.value) === false) {
    // if user selects a invalid letter, nothing changes in the playerAnswerArr
    displayPlayerArray(playerAnswerArr);

    //       - one body part gets added to the hangman

    incorrectGuesses += 1; // incorrectGuesses increases by 1
    // disable the button to prevent the player from selecting it again
    event.target.disabled = true;
    checkForLoss();
  }
  drawCanvas();
}

function checkForWin() {
  if (remainingLetters === 0) { // if the player has guessed all the letters
    wonGame = true;
    // disable the buttons, display the solved gameWord, inform the player that they won, and updatePlayerStats
    letterButton.removeEventListener('click', handleClick);
    displayPlayerArray(playerAnswerArr);
    endMessage.textContent = 'Congrats! You won and saved the hangman!';
    updatePlayerStats();
    //   - refresh page?
  }
}

function checkForLoss() {
  if (remainingLetters > 0 && incorrectGuesses === maxEasyGuesses) {
    wonGame = false;
    //   - hangman will have all parts
    drawCanvas();
    //   - display correct letters in the puzzle as the answer

    // disable the buttons, inform the player that they lost, and updatePlayerStats
    letterButton.removeEventListener('click', handleClick);
    endMessage.textContent = 'You failed to guess \'' + gameWord + '.\' A man has been hanged today. You lose.';
    updatePlayerStats();
    //   - refresh page?
  }
}

function updatePlayerStats() {
  currentPlayer.gamesPlayed ++;
  if (wonGame === true) {
    currentPlayer.totalPoints += 23; ////////THIS WILL PROBABLY CHANGE///////////////
    currentPlayer.gamesWon ++;
  }
  var numberWon = Math.round((currentPlayer.gamesWon / currentPlayer.gamesPlayed) * 100);
  currentPlayer.percentWon = numberWon;
  currentPlayer.percentDisplay = numberWon + '%';
  clearRow();
  sortPlayers();
  setRank();
  renderPlayerStatsRow(currentPlayer);
  // stringify the updated array and set it back to local storage
  storeLocal();
};

function sortPlayers(){
  parsedlclStrgObjArr.sort(function(a, b) {
    if (a.totalPoints === b.totalPoints) {
      return (b.percentWon) - (a.percentWon);
    } else {
      return (b.totalPoints) - (a.totalPoints);
    }
  });
};

function setRank(){
  clearRow();
  var rank = 0;
  var playersLength = parsedlclStrgObjArr.length;
  if (playersLength > 5) {
    playersLength = 5;
  }
  for (var i = 0; i < playersLength; i++) {
    rank = rank + 1;
    parsedlclStrgObjArr[i].ranking = rank;
  }
};

function storeLocal() {
  var playersJSON = JSON.stringify(parsedlclStrgObjArr);
  localStorage.setItem('players', playersJSON);
};

// pass in a word array to select a random word from it to assign to gameWord
function pickWord (wordArr) {
  gameWord = wordArr[generateRandomNumber(wordArr)];
  return gameWord;

  function generateRandomNumber(arr) {
    return Math.floor(Math.random() * arr.length);
  }
}

// initiate the playerAnswerArr to '_' characters, the length of the gameWord
function generatePlayerAnswerArray (gameWord) {
  for (var i = 0; i < gameWord.length; i++) {
    playerAnswerArr.push('_');
  };
}

// display the playerAnswerArr in html
function displayPlayerArray(playerAnswerArr) {
  display.textContent = playerAnswerArr.join(' ');
}

function runGame(){
  playerAnswerArr = [];
  // letterButton.addEventListener('click', handleClick); // listens for a button click
  // letterButton.disabled = false;
  // assign the gameWord
  gameWord = pickWord(easyWords);
  // set the remainingLetters left to guess
  remainingLetters = gameWord.length;
  // generate a playerAnswerArr blank puzzle that is the length of the gameWord and display it
  generatePlayerAnswerArray(gameWord);
  displayPlayerArray(playerAnswerArr);
}

//*****EXECUTE CODE*******************EXECUTE CODE**********************
runGame();

function renderPlayerStatsRow(currentPlayer) {

  var playerStatsTable = document.getElementById('stats_table_body');
  var playerTableRow = document.createElement('tr');
  var rankingPlayer = document.createElement('td');
  var playerNamePlayer = document.createElement('td');
  var gamesPlayedPlayer = document.createElement('td');
  var gamesWonPlayer = document.createElement('td');
  var percentageWonPlayer = document.createElement('td');
  var totalPointsPlayer = document.createElement('td');

  playerTableRow.appendChild(rankingPlayer);

  playerNamePlayer.textContent = currentPlayer.playerName;
  playerTableRow.appendChild(playerNamePlayer);

  gamesPlayedPlayer.textContent = currentPlayer.gamesPlayed;
  playerTableRow.appendChild(gamesPlayedPlayer);

  gamesWonPlayer.textContent = currentPlayer.gamesWon;
  playerTableRow.appendChild(gamesWonPlayer);

  percentageWonPlayer.textContent = currentPlayer.percentDisplay;
  playerTableRow.appendChild(percentageWonPlayer);

  totalPointsPlayer.textContent = currentPlayer.totalPoints;
  playerTableRow.appendChild(totalPointsPlayer);

  if (currentPlayer.ranking <= 5) {
    rankingPlayer.textContent = currentPlayer.ranking;
  } else {
    rankingPlayer.textContent = 'Not Ranked';
  }
  playerStatsTable.appendChild(playerTableRow);
};

function clearRow() {
  var playerStatsTable = document.getElementById('stats_table_body');
  playerStatsTable.textContent = '';
}

// function clearTable(){
//   var playerStatsTable = document.getElementById('stats_table_body');
//   playerStatsTable.textContent = '';
// };
<|endoftext|>


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

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

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

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

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

/* Thanks Reddit
app.post('/gitpull', function(req, res) {
  //GitHub push hook
  res.end();
  if()
  config.secret;
  io.sockets.emit('annouce', {message : 'SYSTEM UPDATE INITIATED...'});
  function puts(error, stdout, stderr) {sys.puts(stdout)}
  exec("git reset --hard HEAD", puts);
  exec("git pull", puts);
  var arr = req.body.commits[0].modified;
  if((arr.join(',').indexOf("app.min.js") > -1) || (arr.join(',').indexOf("app.min.css") > -1) || (arr.join(',').indexOf("index.ejs") > -1)){
    io.sockets.emit('annouce', {message : 'SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NECCESARY.'});
  } else {
    io.sockets.emit('annouce', {message : 'SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NOT NECCESARY.'});
  }
});
*/

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

var users = [];

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

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

io.sockets.on('connection', function (socket) {
  var name = 'Guest' + Math.floor(100 + Math.random() * 900);
  var lastMessage = moment();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  //Begin Handlers
  sendHelp();

  socket.on('config', function (data){
    if(data === undefined || data === null || data.name === undefined || data.name === null){
      console.log('Malformed Config Packet');
      return;
    }
    if(data.name != ''){
      if(typeof data.name != 'string') {
        socket.emit('annouce', {message : "That nick is not a string!"});
        return;
      }
      if(data.name.toLowerCase() == "admin" || data.name.toLowerCase() == "server"){
        socket.emit('annouce', {message : "That nick is reserved!"});
        return;
      }
      if(data.name.toLowerCase().length > 25){
        socket.emit('annouce', {message : "That nick is too long!"});
        return;
      }
      if(data.name.toLowerCase().length == 0){
        socket.emit('annouce', {message : "That nick is too short!"});
        return;
      }
      if(findUser(data.name)){
        socket.emit('annouce', {message : "The nick '" + data.name + "' is taken!"});
      } else {
        name = escapeHtml(data.name);
      }
    }
    broadcast('' + name + ' has entered chat.');
    users.push([name, socket.id, true]);
    io.sockets.emit('users', users);
    socket.emit('name', {name : name});

    //All Other Handlers

    socket.on('broadcast', function (data) {
      if(data === undefined || data === null || data.message === undefined || data.message === null){
        console.log('Malformed Broadcast Packet');
        return;
      }
      if(data.message.length > 500) {
        var help = "Your message was too long (500 character limit).";
        socket.emit('annouce', {message : help});
        return;
      }
      if(moment().diff(lastMessage, 'seconds') < 1) {
        var help = "You are sending too many messages!";
        socket.emit('annouce', {message : help});
        return;
      }
      lastMessage = moment();
      if(data.message[0] == "/") {
        parseServerCommand(data);
      } else {
        bbcode.parse(escapeHtml(data.message), function(content){
          io.sockets.emit('broadcast', {client : name, message : content});
        });
      }
    });

    socket.on('status', function (data) {
      if(data === undefined || data === null || data.status === undefined || data.status === null){
        console.log('Malformed Status Packet');
        return;
      }
      var index = multiArrayIndex(users, [name, socket.id, !data.status]);
      if(index == -1){console.log('missing user: ' + name);return;}
      users[index][2] = data.status;
      io.sockets.emit('users', users);
    });

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

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

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

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

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

/* Thanks Reddit
app.post('/gitpull', function(req, res) {
  //GitHub push hook
  res.end();
  if()
  config.secret;
  io.sockets.emit('annouce', {message : 'SYSTEM UPDATE INITIATED...'});
  function puts(error, stdout, stderr) {sys.puts(stdout)}
  exec("git reset --hard HEAD", puts);
  exec("git pull", puts);
  var arr = req.body.commits[0].modified;
  if((arr.join(',').indexOf("app.min.js") > -1) || (arr.join(',').indexOf("app.min.css") > -1) || (arr.join(',').indexOf("index.ejs") > -1)){
    io.sockets.emit('annouce', {message : 'SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NECCESARY.'});
  } else {
    io.sockets.emit('annouce', {message : 'SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NOT NECCESARY.'});
  }
});
*/

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

var users = [];

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

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

io.sockets.on('connection', function (socket) {
  var name = 'Guest' + Math.floor(100 + Math.random() * 900);
  var lastMessage = moment();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  //Begin Handlers
  sendHelp();

  socket.on('config', function (data){
    if(data === undefined || data === null || data.name === undefined || data.name === null){
      console.log('Malformed Config Packet');
      return;
    }
    if(data.name != ''){
      if(typeof data.name != 'string') {
        socket.emit('annouce', {message : "That nick is not a string!"});
        return;
      }
      if(data.name.toLowerCase() == "admin" || data.name.toLowerCase() == "server"){
        socket.emit('annouce', {message : "That nick is reserved!"});
        return;
      }
      if(data.name.toLowerCase().length > 25){
        socket.emit('annouce', {message : "That nick is too long!"});
        return;
      }
      if(data.name.toLowerCase().length == 0){
        socket.emit('annouce', {message : "That nick is too short!"});
        return;
      }
      if(findUser(data.name)){
        socket.emit('annouce', {message : "The nick '" + data.name + "' is taken!"});
      } else {
        name = escapeHtml(data.name);
      }
    }
    broadcast('' + name + ' has entered chat.');
    users.push([name, socket.id, true]);
    io.sockets.emit('users', users);
    socket.emit('name', {name : name});

    //All Other Handlers

    socket.on('broadcast', function (data) {
      if(data === undefined || data === null || data.message === undefined || data.message === null || typeof data.message != 'string'){
        console.log('Malformed Broadcast Packet');
        return;
      }
      if(data.message.length > 500) {
        var help = "Your message was too long (500 character limit).";
        socket.emit('annouce', {message : help});
        return;
      }
      if(moment().diff(lastMessage, 'seconds') < 1) {
        var help = "You are sending too many messages!";
        socket.emit('annouce', {message : help});
        return;
      }
      lastMessage = moment();
      if(data.message[0] == "/") {
        parseServerCommand(data);
      } else {
        bbcode.parse(escapeHtml(data.message), function(content){
          io.sockets.emit('broadcast', {client : name, message : content});
        });
      }
    });

    socket.on('status', function (data) {
      if(data === undefined || data === null || data.status === undefined || data.status === null){
        console.log('Malformed Status Packet');
        return;
      }
      var index = multiArrayIndex(users, [name, socket.id, !data.status]);
      if(index == -1){console.log('missing user: ' + name);return;}
      users[index][2] = data.status;
      io.sockets.emit('users', users);
    });

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


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

var express = require('express');
var cookieParser = require('cookie-parser');
var compress = require('compression');
var session = require('express-session');
var bodyParser = require('body-parser');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var csrf = require('lusca').csrf();
var methodOverride = require('method-override');

var _ = require('lodash');
var MongoStore = require('connect-mongo')({ session: session });
var flash = require('express-flash');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var expressValidator = require('express-validator');
var connectAssets = require('connect-assets');

/**
 * Load controllers.
 */

var homeController = require('./controllers/home');
var userController = require('./controllers/user');
var apiController = require('./controllers/api');
var pagesController = require('./controllers/pages');
var contactController = require('./controllers/contact');

/**
 * API keys + Passport configuration.
 */

var secrets = require('./config/secrets');
var passportConf = require('./config/passport');

/**
 * Create Express server.
 */

var app = express();

/**
 * Mongoose configuration.
 */

mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
  console.error('MongoDB Connection Error. Make sure MongoDB is running.');
});

var hour = 3600000;
var day = hour * 24;
var week = day * 7;

/**
 * CSRF whitelist.
 */

var csrfExclude = ['/url1', '/url2'];

/**
 * Express configuration.
 */

app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(compress());
app.use(connectAssets({
  paths: [path.join(__dirname, 'public/css'), path.join(__dirname, 'public/js')],
  helperContext: app.locals
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: secrets.sessionSecret,
  store: new MongoStore({
    url: secrets.db,
    autoReconnect: true
  })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function(req, res, next) {
  // CSRF protection.
  if (_.contains(csrfExclude, req.path)) return next();
  csrf(req, res, next);
});
app.use(function(req, res, next) {
  // Make user object available in templates.
  res.locals.user = req.user;
  next();
});
app.use(function(req, res, next) {
  // Remember original destination before login.
  var path = req.path.split('/')[1];
  if (/auth|signin|logout|signup|fonts|favicon/i.test(path)) {
    return next();
  }
  req.session.returnTo = req.path;
  next();
});

app.use(express.static(path.join(__dirname, 'public'), { maxAge: week }));

app.locals.pretty = false;

/**
 * Application routes.
 */

app.get('/', homeController.index);
app.get('/signin', userController.getSignin);
app.post('/signin', userController.postSignin);
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('/dashboard', passportConf.isAuthenticated, userController.getAccount);
app.post('/dashboard/profile', passportConf.isAuthenticated, userController.postUpdateProfile);
app.get('/dashboard/settings', passportConf.isAuthenticated, userController.getDashboardSettings);
app.get('/dashboard/verifications', passportConf.isAuthenticated, userController.getDashboardVerifications);

app.get('/dashboard/change-password', passportConf.isAuthenticated, userController.getDashboardPassword);
app.post('/dashboard/change-password', passportConf.isAuthenticated, userController.postDashboardPassword);
app.post('/dashboard/delete', passportConf.isAuthenticated, userController.postDeleteAccount);
app.get('/dashboard/unlink/:provider', passportConf.isAuthenticated, userController.getOauthUnlink);
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', apiController.getSteam);
app.get('/api/cheerio', apiController.getCheerio);
app.get('/api/twilio', apiController.getTwilio);
app.post('/api/twilio', apiController.postTwilio);
app.get('/api/clockwork', apiController.getClockwork);
app.post('/api/clockwork', apiController.postClockwork);
app.get('/api/foursquare', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFoursquare);
app.get('/api/tumblr', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTumblr);
app.get('/api/facebook', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFacebook);
app.get('/api/github', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getGithub);
app.get('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTwitter);
app.get('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getVenmo);
app.post('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.postVenmo);
app.get('/api/linkedin', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getLinkedin);
app.get('/api/d3', apiController.getD3);

/** Stripe API **/
app.get('/api/stripe', apiController.getStripe);
app.get('/api/stripe/charge', apiController.getStripeCharge);
app.post('/api/stripe/onetime', apiController.postStripeCharge);
app.get('/api/stripe/subscriptions', apiController.getStripeSubscriptions);
app.post('/api/stripe/subscriptions', apiController.postStripeSubscriptions);
app.get('/api/stripe/customers', apiController.getStripeCustomers);

/** Pages Routes **/
app.get('/pages/jobs', pagesController.getJobs);
app.get('/pages/our-team', pagesController.getOurTeam);
app.get('/pages/press', pagesController.getPress);
app.get('/pages/how-it-works', pagesController.getHowItWorks);
app.get('/pages/terms-of-use', pagesController.getTermsOfUse);
app.get('/pages/privacy-policy', pagesController.getPrivacyPolicy);
app.get('/pages/about-us', pagesController.getAboutUs);
app.get('/pages/faqs', pagesController.getFaqs);
app.get('/pages/getting-started', pagesController.getGettingStarted);
app.get('/pages/contact-us', contactController.getContact);
app.post('/pages/contact-us', contactController.postContact);

/**
 * OAuth routes for sign-in.
 */

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

/**
 * OAuth routes for API examples that require authorization.
 */

app.get('/auth/foursquare', passport.authorize('foursquare'));
app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/foursquare');
});
app.get('/auth/tumblr', passport.authorize('tumblr'));
app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/tumblr');
});
app.get('/auth/venmo', passport.authorize('venmo', { scope: 'make_payments access_profile access_balance access_email access_phone' }));
app.get('/auth/venmo/callback', passport.authorize('venmo', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/venmo');
});

/**
 * 404 Error Handler.
 */

app.use(function(req, res) {
  res.status(404);
  res.render('404', {title: 'Error 404 - Page Not Found'});
});

/**
 * 500 Error Handler.
 */

app.use(errorHandler());

/**
 * Start Express server.
 */

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

module.exports = app;
<commit_msg>Resolving broken codebase with lodash 4 not compatible: _.contains() is not a function<commit_after>/**
 * Module dependencies.
 */

var express = require('express');
var cookieParser = require('cookie-parser');
var compress = require('compression');
var session = require('express-session');
var bodyParser = require('body-parser');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var csrf = require('lusca').csrf();
var methodOverride = require('method-override');

var _ = require('lodash');
var MongoStore = require('connect-mongo')({ session: session });
var flash = require('express-flash');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var expressValidator = require('express-validator');
var connectAssets = require('connect-assets');

/**
 * Load controllers.
 */

var homeController = require('./controllers/home');
var userController = require('./controllers/user');
var apiController = require('./controllers/api');
var pagesController = require('./controllers/pages');
var contactController = require('./controllers/contact');

/**
 * API keys + Passport configuration.
 */

var secrets = require('./config/secrets');
var passportConf = require('./config/passport');

/**
 * Create Express server.
 */

var app = express();

/**
 * Mongoose configuration.
 */

mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
  console.error('MongoDB Connection Error. Make sure MongoDB is running.');
});

var hour = 3600000;
var day = hour * 24;
var week = day * 7;

/**
 * CSRF whitelist.
 */

var csrfExclude = ['/url1', '/url2'];

/**
 * Express configuration.
 */

app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(compress());
app.use(connectAssets({
  paths: [path.join(__dirname, 'public/css'), path.join(__dirname, 'public/js')],
  helperContext: app.locals
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: secrets.sessionSecret,
  store: new MongoStore({
    url: secrets.db,
    autoReconnect: true
  })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function(req, res, next) {
  // CSRF protection.
  if (_.includes(csrfExclude, req.path)) return next();
  csrf(req, res, next);
});
app.use(function(req, res, next) {
  // Make user object available in templates.
  res.locals.user = req.user;
  next();
});
app.use(function(req, res, next) {
  // Remember original destination before login.
  var path = req.path.split('/')[1];
  if (/auth|signin|logout|signup|fonts|favicon/i.test(path)) {
    return next();
  }
  req.session.returnTo = req.path;
  next();
});

app.use(express.static(path.join(__dirname, 'public'), { maxAge: week }));

app.locals.pretty = false;

/**
 * Application routes.
 */

app.get('/', homeController.index);
app.get('/signin', userController.getSignin);
app.post('/signin', userController.postSignin);
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('/dashboard', passportConf.isAuthenticated, userController.getAccount);
app.post('/dashboard/profile', passportConf.isAuthenticated, userController.postUpdateProfile);
app.get('/dashboard/settings', passportConf.isAuthenticated, userController.getDashboardSettings);
app.get('/dashboard/verifications', passportConf.isAuthenticated, userController.getDashboardVerifications);

app.get('/dashboard/change-password', passportConf.isAuthenticated, userController.getDashboardPassword);
app.post('/dashboard/change-password', passportConf.isAuthenticated, userController.postDashboardPassword);
app.post('/dashboard/delete', passportConf.isAuthenticated, userController.postDeleteAccount);
app.get('/dashboard/unlink/:provider', passportConf.isAuthenticated, userController.getOauthUnlink);
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', apiController.getSteam);
app.get('/api/cheerio', apiController.getCheerio);
app.get('/api/twilio', apiController.getTwilio);
app.post('/api/twilio', apiController.postTwilio);
app.get('/api/clockwork', apiController.getClockwork);
app.post('/api/clockwork', apiController.postClockwork);
app.get('/api/foursquare', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFoursquare);
app.get('/api/tumblr', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTumblr);
app.get('/api/facebook', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFacebook);
app.get('/api/github', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getGithub);
app.get('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTwitter);
app.get('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getVenmo);
app.post('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.postVenmo);
app.get('/api/linkedin', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getLinkedin);
app.get('/api/d3', apiController.getD3);

/** Stripe API **/
app.get('/api/stripe', apiController.getStripe);
app.get('/api/stripe/charge', apiController.getStripeCharge);
app.post('/api/stripe/onetime', apiController.postStripeCharge);
app.get('/api/stripe/subscriptions', apiController.getStripeSubscriptions);
app.post('/api/stripe/subscriptions', apiController.postStripeSubscriptions);
app.get('/api/stripe/customers', apiController.getStripeCustomers);

/** Pages Routes **/
app.get('/pages/jobs', pagesController.getJobs);
app.get('/pages/our-team', pagesController.getOurTeam);
app.get('/pages/press', pagesController.getPress);
app.get('/pages/how-it-works', pagesController.getHowItWorks);
app.get('/pages/terms-of-use', pagesController.getTermsOfUse);
app.get('/pages/privacy-policy', pagesController.getPrivacyPolicy);
app.get('/pages/about-us', pagesController.getAboutUs);
app.get('/pages/faqs', pagesController.getFaqs);
app.get('/pages/getting-started', pagesController.getGettingStarted);
app.get('/pages/contact-us', contactController.getContact);
app.post('/pages/contact-us', contactController.postContact);

/**
 * OAuth routes for sign-in.
 */

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

/**
 * OAuth routes for API examples that require authorization.
 */

app.get('/auth/foursquare', passport.authorize('foursquare'));
app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/foursquare');
});
app.get('/auth/tumblr', passport.authorize('tumblr'));
app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/tumblr');
});
app.get('/auth/venmo', passport.authorize('venmo', { scope: 'make_payments access_profile access_balance access_email access_phone' }));
app.get('/auth/venmo/callback', passport.authorize('venmo', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/venmo');
});

/**
 * 404 Error Handler.
 */

app.use(function(req, res) {
  res.status(404);
  res.render('404', {title: 'Error 404 - Page Not Found'});
});

/**
 * 500 Error Handler.
 */

app.use(errorHandler());

/**
 * Start Express server.
 */

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

module.exports = app;
<|endoftext|>


<commit_before>var express = require('express'),
	routes = require('./routes'),
	path = require('path'),
	config = require('./config'),
	async = require('async'),
	gpio = require('pi-gpio'),
	app = express();

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

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

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

app.get("/api/ping", function(req, res) {
	res.json("pong");
});

app.post("/api/garage/left", function(req, res) {
	async.series([
		function(callback) {
			// Open pin for output
			gpio.open(config.LEFT_GARAGE_PIN, "output", callback);
		},
		function(callback) {
			// Turn the relay on
			gpio.write(config.LEFT_GARAGE_PIN, config.RELAY_ON, callback);
		},
		function(callback) {
			// Turn the relay off after delay to simulate button press
			delayPinWrite(config.LEFT_GARAGE_PIN, config.RELAY_OFF, callback);
		},
		function(err, results) {
			setTimeout(function() {
				// Close pin from further writing
				gpio.close(config.LEFT_GARAGE_PIN);
				// Return json
				res.json("ok");
			}, config.RELAY_TIMEOUT);
		}
	]);
});

app.post("/api/garage/right", function(req, res) {
	async.series([
		function(callback) {
			// Open pin for output
			gpio.open(config.RIGHT_GARAGE_PIN, "output", callback);
		},
		function(callback) {
			// Turn the relay on
			gpio.write(config.RIGHT_GARAGE_PIN, config.RELAY_ON, callback);
		},
		function(callback) {
			// Turn the relay off after delay to simulate button press
			delayPinWrite(config.RIGHT_GARAGE_PIN, config.RELAY_OFF, callback);
		},
		function(err, results) {
			setTimeout(function() {
				// Close pin from further writing
				gpio.close(config.RIGHT_GARAGE_PIN);
				// Return json
				res.json("ok");
			}, config.RELAY_TIMEOUT);
		}
	]);
});

app.post("/api/garage/both", function(req, res) {
	async.series([
		function(callback) {
			// Open pin for output
			gpio.open(config.LEFT_GARAGE_PIN, "output", callback);
		},
		function(callback) {
			// Open pin for output
			gpio.open(config.RIGHT_GARAGE_PIN, "output", callback);
		},
		function(callback) {
			// Turn the relay on
			gpio.write(config.LEFT_GARAGE_PIN, config.RELAY_ON, callback);
		},
		function(callback) {
			// Turn the relay on
			gpio.write(config.RIGHT_GARAGE_PIN, config.RELAY_ON, callback);
		},
		function(callback) {
			// Turn the relay off after delay to simulate button press
			delayPinWrite(config.LEFT_GARAGE_PIN, config.RELAY_OFF, callback);
		},
		function(callback) {
			// Turn the relay off after delay to simulate button press
			delayPinWrite(config.RIGHT_GARAGE_PIN, config.RELAY_OFF, callback);
		},
		function(err, results) {
			setTimeout(function() {
				// Close pin from further writing
				gpio.close(config.LEFT_GARAGE_PIN);
				gpio.close(config.RIGHT_GARAGE_PIN);
				// Return json
				res.json("ok");
			}, config.RELAY_TIMEOUT);
		}
	]);
});

app.listen(app.get('port'));
<commit_msg>New index view.<commit_after>var express = require('express'),
	path = require('path'),
	config = require('./config'),
	async = require('async'),
	gpio = require('pi-gpio'),
	app = express();

app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);

app.use('/', express.static(__dirname + '/public'));

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

app.get("/api/ping", function(req, res) {
	res.json("pong");
});

app.post("/api/garage/left", function(req, res) {
	async.series([
		function(callback) {
			// Open pin for output
			gpio.open(config.LEFT_GARAGE_PIN, "output", callback);
		},
		function(callback) {
			// Turn the relay on
			gpio.write(config.LEFT_GARAGE_PIN, config.RELAY_ON, callback);
		},
		function(callback) {
			// Turn the relay off after delay to simulate button press
			delayPinWrite(config.LEFT_GARAGE_PIN, config.RELAY_OFF, callback);
		},
		function(err, results) {
			setTimeout(function() {
				// Close pin from further writing
				gpio.close(config.LEFT_GARAGE_PIN);
				// Return json
				res.json("ok");
			}, config.RELAY_TIMEOUT);
		}
	]);
});

app.post("/api/garage/right", function(req, res) {
	async.series([
		function(callback) {
			// Open pin for output
			gpio.open(config.RIGHT_GARAGE_PIN, "output", callback);
		},
		function(callback) {
			// Turn the relay on
			gpio.write(config.RIGHT_GARAGE_PIN, config.RELAY_ON, callback);
		},
		function(callback) {
			// Turn the relay off after delay to simulate button press
			delayPinWrite(config.RIGHT_GARAGE_PIN, config.RELAY_OFF, callback);
		},
		function(err, results) {
			setTimeout(function() {
				// Close pin from further writing
				gpio.close(config.RIGHT_GARAGE_PIN);
				// Return json
				res.json("ok");
			}, config.RELAY_TIMEOUT);
		}
	]);
});

app.post("/api/garage/both", function(req, res) {
	async.series([
		function(callback) {
			// Open pin for output
			gpio.open(config.LEFT_GARAGE_PIN, "output", callback);
		},
		function(callback) {
			// Open pin for output
			gpio.open(config.RIGHT_GARAGE_PIN, "output", callback);
		},
		function(callback) {
			// Turn the relay on
			gpio.write(config.LEFT_GARAGE_PIN, config.RELAY_ON, callback);
		},
		function(callback) {
			// Turn the relay on
			gpio.write(config.RIGHT_GARAGE_PIN, config.RELAY_ON, callback);
		},
		function(callback) {
			// Turn the relay off after delay to simulate button press
			delayPinWrite(config.LEFT_GARAGE_PIN, config.RELAY_OFF, callback);
		},
		function(callback) {
			// Turn the relay off after delay to simulate button press
			delayPinWrite(config.RIGHT_GARAGE_PIN, config.RELAY_OFF, callback);
		},
		function(err, results) {
			setTimeout(function() {
				// Close pin from further writing
				gpio.close(config.LEFT_GARAGE_PIN);
				gpio.close(config.RIGHT_GARAGE_PIN);
				// Return json
				res.json("ok");
			}, config.RELAY_TIMEOUT);
		}
	]);
});

app.listen(app.get('port'));
<|endoftext|>


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

var port = process.env.PORT || 5000;

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Live on heroku.\n');
}).listen(port, '127.0.0.1');

console.log('Server running at localhost:' + port + '/');
<commit_msg>possibly fixed the listen port issue.<commit_after>var http = require('http');

var port = process.env.PORT || 5000;

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Live on heroku.\n');
}).listen(port);

console.log('Server running at localhost:' + port + '/');
<|endoftext|>


<commit_before>/*jslint nodejs: true*/

var express = require('express'),
    iefix = require('express-ie-cors'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    app = module.exports = express();

app.use(iefix({ contentType: 'application/x-www-form-urlencoded' }));
app.use(bodyParser.json());
app.use(cors());

function notSupported(req, res) {
  var error = {
    "request_type": "atomic",
    "response_code": 500,
    "resource_status": [
      {
        "resource": "*",
        "response_code": 500,
        "errors": [
          {
            "code": "NOT_SUPPORTED",
            "description": "The system does not support resources of this type."
          }
        ]
      }
    ]
  };

  return res.status(400).send(error);
}

app.get('/api/v1/', notSupported);

if (!module.parent) {
  var port = 4000;
  app.listen(port, function() {
    console.log('Listening on %d.', port);
  });
}

<commit_msg>Correct response code<commit_after>/*jslint nodejs: true*/

var express = require('express'),
    iefix = require('express-ie-cors'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    app = module.exports = express();

app.use(iefix({ contentType: 'application/x-www-form-urlencoded' }));
app.use(bodyParser.json());
app.use(cors());

function notSupported(req, res) {
  var error = {
    "request_type": "atomic",
    "response_code": 500,
    "resource_status": [
      {
        "resource": "*",
        "response_code": 500,
        "errors": [
          {
            "code": "NOT_SUPPORTED",
            "description": "The system does not support resources of this type."
          }
        ]
      }
    ]
  };

  return res.status(500).send(error);
}

app.get('/api/v1/', notSupported);

if (!module.parent) {
  var port = 4000;
  app.listen(port, function() {
    console.log('Listening on %d.', port);
  });
}

<|endoftext|>


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

var index = require('./routes/index');
var users = require('./routes/users');
var item = require('./routes/item');
var category = require('./routes/category')
var retur = require('./routes/retur')
var auth = require('./routes/auth');
var inner = require('./routes/inner');
var warehouse = require('./routes/warehouse');
var carton = require('./routes/carton');
var innerGrade = require('./routes/innergrade');
var innerSource = require('./routes/innersource');
var config = require('./config/config');
var cors = require('cors')

require('dotenv').config()

mongoose.connect(process.env.MONGO_URL, { useMongoClient: true }, err=>{
  var acl = new nodeAcl(new nodeAcl.mongodbBackend(mongoose.connection.db, ''));
  app.set('acl', acl)
  app.set('mongo', mongoose.connection.db)
  // sementara tak taruh sini seeder acl-nya :D (mnirfan)
  acl.allow('admin', 'item', ['GET', 'POST', 'DELETE'])
  acl.allow('admin', 'category', ['GET', 'POST', 'DELETE'])
  acl.allow('admin', 'user', ['GET', 'POST', 'DELETE'])
  acl.allow('basic', 'item', ['GET'])
  acl.addUserRoles('1', 'admin') // irfan
  acl.addUserRoles('21', 'basic') //arnaz
})

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

// view engine setup

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

app.set('superSecret',config.secret)

// acl.whatResources('lolaa', (err, res)=>{
//   console.log("debuggg");
//   console.log(res);
//   console.log(err);
// })

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

console.log('pada NODE_ENV : ', process.env.NODE_ENV);

//use cors
app.use(cors())

//verify token
router.use(function(req, res, next){

  var head = req.headers.authorization ? req.headers.authorization.split(' ') : ''
  var token = null

  if(head.length == 2){
    var scheme = head[0]
    if(/^Bearer$/i.test(scheme)){
      token = head[1]
      jwt.verify(token, app.get('superSecret'), function (err, decoded) {
        if(err){
          res.json({
            success: false,
            message: 'Failed to authenticate token.'
          })
        }else {
          req.decoded = decoded;
          next();
        }
      })}
  }else {
    return res.status(403).send({
       success: false,
       message: 'No token provided.'
   })
  }
})

app.use('/api',router);
app.use('/', index);
app.use('/api/user', users);
app.use('/api/item', item);
app.use('/api/category', category);
app.use('/api/inner', inner);
app.use('/api/innergrade', innerGrade);
app.use('/api/innersource', innerSource);
app.use('/api/warehouse', warehouse);
app.use('/api/carton', carton);
app.use('/api/retur', retur);
app.use('/auth', auth);

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

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

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

module.exports = app;
<commit_msg>tambah create output, list all output<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var nodeAcl = require('acl');
var mongoose = require('mongoose');

var index = require('./routes/index');
var users = require('./routes/users');
var item = require('./routes/item');
var output = require('./routes/output');
var category = require('./routes/category')
var retur = require('./routes/retur')
var auth = require('./routes/auth');
var deliveryOrder = require('./routes/deliveryorder');
var inner = require('./routes/inner');
var warehouse = require('./routes/warehouse');
var carton = require('./routes/carton');
var innerGrade = require('./routes/innergrade');
var innerSource = require('./routes/innersource');
var config = require('./config/config');
var cors = require('cors')

require('dotenv').config()

mongoose.connect(process.env.MONGO_URL, { useMongoClient: true }, err=>{
  var acl = new nodeAcl(new nodeAcl.mongodbBackend(mongoose.connection.db, ''));
  app.set('acl', acl)
  app.set('mongo', mongoose.connection.db)
  // sementara tak taruh sini seeder acl-nya :D (mnirfan)
  acl.allow('admin', 'item', ['GET', 'POST', 'DELETE'])
  acl.allow('admin', 'category', ['GET', 'POST', 'DELETE'])
  acl.allow('admin', 'user', ['GET', 'POST', 'DELETE'])
  acl.allow('basic', 'item', ['GET'])
  acl.addUserRoles('1', 'admin') // irfan
  acl.addUserRoles('21', 'basic') //arnaz
})

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

// view engine setup

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

app.set('superSecret',config.secret)

// acl.whatResources('lolaa', (err, res)=>{
//   console.log("debuggg");
//   console.log(res);
//   console.log(err);
// })

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

console.log('pada NODE_ENV : ', process.env.NODE_ENV);

//use cors
app.use(cors())

//verify token
router.use(function(req, res, next){

  var head = req.headers.authorization ? req.headers.authorization.split(' ') : ''
  var token = null

  if(head.length == 2){
    var scheme = head[0]
    if(/^Bearer$/i.test(scheme)){
      token = head[1]
      jwt.verify(token, app.get('superSecret'), function (err, decoded) {
        if(err){
          res.json({
            success: false,
            message: 'Failed to authenticate token.'
          })
        }else {
          req.decoded = decoded;
          next();
        }
      })}
  }else {
    return res.status(403).send({
       success: false,
       message: 'No token provided.'
   })
  }
})

app.use('/api',router);
app.use('/', index);
app.use('/api/user', users);
app.use('/api/item', item);
app.use('/api/category', category);
app.use('/api/inner', inner);
app.use('/api/innergrade', innerGrade);
app.use('/api/innersource', innerSource);
app.use('/api/warehouse', warehouse);
app.use('/api/carton', carton);
app.use('/api/retur', retur);
app.use('/api/output', output);
app.use('/api/deliveryorder', deliveryOrder);
app.use('/auth', auth);

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

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

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

module.exports = app;
<|endoftext|>