<commit_before>'use strict';

const hapi      = require('hapi');
const server    = new hapi.Server();
const validator = require('validator');
const mongoose  = require('mongoose');
const Person    = mongoose.model('Person',
                      { name: {
                          type: String,
                          required: true
                        },
                        email: {
                          type: String,
                          required: true,
                          unique: true,
                          validator: (value) =>
                             validator.isEmail(value)
                        },
                        availability: {
                          type: String,
                          enum: ["morning", "afternoon", "both", "none"]
                        }
                     }
                  );

mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/coffee-talk');

server.connection({ port: process.env.PORT || 3000 });

server.register([require('vision'), require('inert')], (err) => {
  server.views({
    engines: {
        ejs: require('ejs')
    },
    relativeTo: __dirname,
    path: 'templates'
  });

  server.route({
      method: 'GET',
      path: '/',
      handler: {
          view: 'index'
      }
  });

  server.route({
    method: 'POST',
    path: '/signup',
    handler: function (request, reply) {
      const { name, email, availability } = request.payload
      const person = new Person({ name, email, availability })

      person.save(function (err) {
        if (err) {
          console.log(err)
          reply.redirect('/?signup=failure')
        } else {
          reply.redirect('/?signup=success')
        }
      })
    }
  });

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

server.start((err) => {
  if (err) {
    throw err
  }

  console.log(`Server running at: ${server.info.uri}`)
});<commit_msg>initial unsubscribe user<commit_after>'use strict';

const hapi      = require('hapi');
const server    = new hapi.Server();
const validator = require('validator');
const mongoose  = require('mongoose');
const Person    = mongoose.model('Person',
                      { name: {
                          type: String,
                          required: true
                        },
                        email: {
                          type: String,
                          required: true,
                          unique: true,
                          validator: (value) =>
                             validator.isEmail(value)
                        },
                        availability: {
                          type: String,
                          enum: ["morning", "afternoon", "both", "none"]
                        }
                     }
                  );

mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/coffee-talk');

server.connection({ port: process.env.PORT || 3000 });

server.register([require('vision'), require('inert')], (err) => {
  server.views({
    engines: {
        ejs: require('ejs')
    },
    relativeTo: __dirname,
    path: 'templates'
  });

  server.route({
      method: 'GET',
      path: '/',
      handler: {
          view: 'index'
      }
  });

  server.route({
    method: 'POST',
    path: '/signup',
    handler: function (request, reply) {
      const { name, email, availability } = request.payload
      const person = new Person({ name, email, availability })

      person.save(function (err) {
        if (err) {
          console.log(err)
          reply.redirect('/?signup=failure')
        } else {
          reply.redirect('/?signup=success')
        }
      })
    }
  });

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

// route unsubscribe email
  server.route({
      method: 'GET',
      path: '/unsubscribe',
      handler: function(request, reply) {
          const { email } = request.query

          Person.findOneAndRemove({email: email}, function(err, person) {
              if (err){
                  console.log(err)
                  reply.redirect('/?message="User does not exist"')
              }else{
                  reply.redirect('/?message="You have been unsubscribed"')
              }
          });
      }
  });

server.start((err) => {
  if (err) {
    throw err
  }

  console.log(`Server running at: ${server.info.uri}`)
});<|endoftext|>


<commit_before>var express       = require('express');
var request       = require('request');
var redis         = require('redis');
var cookieSession = require('cookie-session');
var config        = require('./config');
var kanye         = require('./kanye');
var twilio        = require('twilio')(config.ACCOUNT_SID, config.AUTH_TOKEN);

// Start the express app
var app = express();
app.use(express.static(__dirname + '/static'));
app.use(cookieSession({ keys: [config.SECRET_KEY]}));

var redisClient = redis.createClient();

var KANYE_PORT = config.DEBUG ? 8000 : 80;
// Services object
var SERVICES = {
  advice    : 'http://127.0.0.1:3000',
  hn        : 'http://127.0.0.1:3001',
  wolfram   : 'http://127.0.0.1:4000',
  reddit    : 'http://127.0.0.1:3002',
  inbox     : 'http://127.0.0.1:3003',
  getServiceFromMessage: function(message) {
    // This will return null if no service found.
    return this[message.toLowerCase().split(/\s+/)[0]];
  }
};

// XXX eventually register services and ask this, or figure it out
// somehow non-hacky
var isServiceStateless = function(service) {
  if (service === SERVICES['advice']) {
    return true;
  }
  return false;
};

// Global variable keeps track of the last service that was used by a number.
var g_lastService = {};
// Global variable tracks if a number is waiting for a response.
var g_isWaiting = {};

// The front-end stuff originates from here
app.get('/', function(req, res) {
  res.sendfile(__dirname + "/static/index.html");
});

/*
  Utility endpoint. Allows us to test without sending a text message.
  To use:
    1. Start the server and go to the /test?m={message}
    2. The page should respond with what it would normally text you
*/
app.get('/test', function(req, res) {
  var testParams = {
    From: '+5555555555',
    Body: req.query.m,
    Test: true,
  };

  if (config.DEBUG) {
    console.log('Sending test params...');
    console.log( testParams);
  }

  request({ url: 'http://localhost:' + KANYE_PORT + '/sms', qs: testParams },
    function(error, response, body) {
      if (error) {
        res.status(500).send('Test failed to send. ' + error);
        return;
      }

      res.status(200).send(body);
    });
});

/*
  // **** START GMAIL AUTHORIZATION CODE ****
  This endpoint handles authentication with GMail.
*/

app.get('/gmail', function(req, res) {
  var userNumber = req.query.number;

  request({ url: SERVICES.inbox + '/auth_url', qs: { number: userNumber } },
    function(error, response, body) {
      // Set the cookie for later use.
      req.session.number = userNumber;
      // Body contains the URL to get to.
      res.cookie({ number: userNumber }).redirect(body);
    });
});

// Called right after they authenticate in /gmail
app.get('/oauth2callback', function(req, res) {
  var authorizationCode = req.query.code;
  var number = req.session.number;

  request({ url: SERVICES.inbox + '/get_tokens', qs: { code: authorizationCode, number: number }},
    function(error, response, body) {
      if (error) {
        res.status(500).send('Failed to get authentication token.');
        return;
      }

      res.status(200).send('Token authentication successful. You can now use the inbox command');
    });
});

// **** END GMAIL AUTHORIZATION CODE ****

var sendBodyResult = function(number, body, res) {
  var bodyJSON = body ? JSON.parse( body ) : {};
  var outgoingMessage = bodyJSON.message;
  var outgoingMedia   = bodyJSON.media;
  var outgoingError   = bodyJSON.error;

  if (outgoingError) {
    if (isLocalTest) {
      res.status(200).send(outgoingError);
    } else {
      kanye.sendMessage(number, outgoingError);
    }
    return;
  }

  // Instead of sending a test message, inline the result directly to webpage.
  if (isLocalTest) {
    res.status(200).send(outgoingMessage);
  } else {
    // Send the outgoing message back to the user
    kanye.sendMessage(number, outgoingMessage, outgoingMedia);
    res.status(200).end();
  }
}

// Twilio will ping this when we receieve an SMS
app.get('/sms', function(req, res) {
  var isLocalTest = req.query.Test;
  var number      = req.query.From;
  var message     = req.query.Body;
  var lastService = g_lastService[number];

  if (g_isWaiting[number]) {
    var waitingErrorMessage = 'Sorry, I\'m really busy right now. Hit me up later.';
    kanye.sendMessage(number, waitingErrorMessage);
    return;
  }
  g_isWaiting[number] = true;

  var service;

  if (config.DEBUG) {
    console.log('Received SMS: %s | Last service: %s', message, lastService);
  }

  if (SERVICES.getServiceFromMessage(message)) {
    service = SERVICES.getServiceFromMessage(message);

    // They have started a new service. Clear the session for the last service they were on.
    if (lastService) {
      // Note the empty function is required so the app will not crash if the
      // `/clear` endpoint does not exist.
      request(service + "/clear?number=" + number, function() {});
    }

    // Remember the service for next time
    if (isServiceStateless(service)) {
      g_lastService[number] = undefined;
    } else {
      g_lastService[number] = service;
    }
  } else if (lastService) {
    // They didn't match a service, so they may be exploring the last service they were on.
    service = lastService;
  } else {
    service = SERVICES.wolfram;
    console.log('Falling back to Wolfram Alpha service.');
  }

  kanye.serviceRequest(service, message, number, function(error, response, body) {
    g_isWaiting[number] = false;
    if (error || response.statusCode != 200) {
      // Send a 'try again later' message.'
      if (service === SERVICES.wolfram) {
        var errorMessage = 'Sorry, I\'m really busy right now. Hit me up later.';
        kanye.sendMessage(number, errorMessage);
      } else {
        kanye.serviceRequest(service, message, number, function(error, response, body) {
          sendBodyResult(number, body, res);
        });
      }
      return;
    }
    sendBodyResult(number, body, res);
  });
});

app.get('/sendsms', function(req, res) {
  var message = req.query.message;
  var number = req.query.number;
  var media = req.query.media;

  if (media) {
    console.log("SENT MMS");
    twilio.sendMessage({
      to: number,
      from: config.PHONE_NUMBER,
      mediaUrl: media,
      body: unescape(message)
    });
  } else {
    twilio.sendMessage({
      to: number,
      from: config.PHONE_NUMBER,
      body: unescape(message)
    });
  }

  res.status(200).end();
});

app.listen(KANYE_PORT);
console.log('Kanye is at port ' + KANYE_PORT + ' and is ready to help.');
<commit_msg>This sucks<commit_after>var express       = require('express');
var request       = require('request');
var redis         = require('redis');
var cookieSession = require('cookie-session');
var config        = require('./config');
var kanye         = require('./kanye');
var twilio        = require('twilio')(config.ACCOUNT_SID, config.AUTH_TOKEN);

// Start the express app
var app = express();
app.use(express.static(__dirname + '/static'));
app.use(cookieSession({ keys: [config.SECRET_KEY]}));

var redisClient = redis.createClient();

var KANYE_PORT = config.DEBUG ? 8000 : 80;
// Services object
var SERVICES = {
  advice    : 'http://127.0.0.1:3000',
  hn        : 'http://127.0.0.1:3001',
  wolfram   : 'http://127.0.0.1:4000',
  reddit    : 'http://127.0.0.1:3002',
  inbox     : 'http://127.0.0.1:3003',
  getServiceFromMessage: function(message) {
    // This will return null if no service found.
    return this[message.toLowerCase().split(/\s+/)[0]];
  }
};

// XXX eventually register services and ask this, or figure it out
// somehow non-hacky
var isServiceStateless = function(service) {
  if (service === SERVICES['advice']) {
    return true;
  }
  return false;
};

// Global variable keeps track of the last service that was used by a number.
var g_lastService = {};
// Global variable tracks if a number is waiting for a response.
var g_isWaiting = {};

// The front-end stuff originates from here
app.get('/', function(req, res) {
  res.sendfile(__dirname + "/static/index.html");
});

/*
  Utility endpoint. Allows us to test without sending a text message.
  To use:
    1. Start the server and go to the /test?m={message}
    2. The page should respond with what it would normally text you
*/
app.get('/test', function(req, res) {
  var testParams = {
    From: '+5555555555',
    Body: req.query.m,
    Test: true,
  };

  if (config.DEBUG) {
    console.log('Sending test params...');
    console.log( testParams);
  }

  request({ url: 'http://localhost:' + KANYE_PORT + '/sms', qs: testParams },
    function(error, response, body) {
      if (error) {
        res.status(500).send('Test failed to send. ' + error);
        return;
      }

      res.status(200).send(body);
    });
});

/*
  // **** START GMAIL AUTHORIZATION CODE ****
  This endpoint handles authentication with GMail.
*/

app.get('/gmail', function(req, res) {
  var userNumber = req.query.number;

  request({ url: SERVICES.inbox + '/auth_url', qs: { number: userNumber } },
    function(error, response, body) {
      // Set the cookie for later use.
      req.session.number = userNumber;
      // Body contains the URL to get to.
      res.cookie({ number: userNumber }).redirect(body);
    });
});

// Called right after they authenticate in /gmail
app.get('/oauth2callback', function(req, res) {
  var authorizationCode = req.query.code;
  var number = req.session.number;

  request({ url: SERVICES.inbox + '/get_tokens', qs: { code: authorizationCode, number: number }},
    function(error, response, body) {
      if (error) {
        res.status(500).send('Failed to get authentication token.');
        return;
      }

      res.status(200).send('Token authentication successful. You can now use the inbox command');
    });
});

// **** END GMAIL AUTHORIZATION CODE ****

var sendBodyResult = function(number, body, res, isLocalTest) {
  var bodyJSON = body ? JSON.parse( body ) : {};
  var outgoingMessage = bodyJSON.message;
  var outgoingMedia   = bodyJSON.media;
  var outgoingError   = bodyJSON.error;

  if (outgoingError) {
    if (isLocalTest) {
      res.status(200).send(outgoingError);
    } else {
      kanye.sendMessage(number, outgoingError);
    }
    return;
  }

  // Instead of sending a test message, inline the result directly to webpage.
  if (isLocalTest) {
    res.status(200).send(outgoingMessage);
  } else {
    // Send the outgoing message back to the user
    kanye.sendMessage(number, outgoingMessage, outgoingMedia);
    res.status(200).end();
  }
}

// Twilio will ping this when we receieve an SMS
app.get('/sms', function(req, res) {
  var isLocalTest = req.query.Test;
  var number      = req.query.From;
  var message     = req.query.Body;
  var lastService = g_lastService[number];

  if (g_isWaiting[number]) {
    var waitingErrorMessage = 'Sorry, I\'m really busy right now. Hit me up later.';
    kanye.sendMessage(number, waitingErrorMessage);
    return;
  }
  g_isWaiting[number] = true;

  var service;

  if (config.DEBUG) {
    console.log('Received SMS: %s | Last service: %s', message, lastService);
  }

  if (SERVICES.getServiceFromMessage(message)) {
    service = SERVICES.getServiceFromMessage(message);

    // They have started a new service. Clear the session for the last service they were on.
    if (lastService) {
      // Note the empty function is required so the app will not crash if the
      // `/clear` endpoint does not exist.
      request(service + "/clear?number=" + number, function() {});
    }

    // Remember the service for next time
    if (isServiceStateless(service)) {
      g_lastService[number] = undefined;
    } else {
      g_lastService[number] = service;
    }
  } else if (lastService) {
    // They didn't match a service, so they may be exploring the last service they were on.
    service = lastService;
  } else {
    service = SERVICES.wolfram;
    console.log('Falling back to Wolfram Alpha service.');
  }

  kanye.serviceRequest(service, message, number, function(error, response, body) {
    g_isWaiting[number] = false;
    if (error || response.statusCode != 200) {
      // Send a 'try again later' message.'
      if (service === SERVICES.wolfram) {
        var errorMessage = 'Sorry, I\'m really busy right now. Hit me up later.';
        kanye.sendMessage(number, errorMessage);
      } else {
        kanye.serviceRequest(service, message, number, function(error, response, body) {
          sendBodyResult(number, body, res, isLocalTest);
        });
      }
      return;
    }
    sendBodyResult(number, body, res, isLocalTest);
  });
});

app.get('/sendsms', function(req, res) {
  var message = req.query.message;
  var number = req.query.number;
  var media = req.query.media;

  if (media) {
    console.log("SENT MMS");
    twilio.sendMessage({
      to: number,
      from: config.PHONE_NUMBER,
      mediaUrl: media,
      body: unescape(message)
    });
  } else {
    twilio.sendMessage({
      to: number,
      from: config.PHONE_NUMBER,
      body: unescape(message)
    });
  }

  res.status(200).end();
});

app.listen(KANYE_PORT);
console.log('Kanye is at port ' + KANYE_PORT + ' and is ready to help.');
<|endoftext|>


<commit_before>// Here we take the user's name as input to personalize the game
var userName = prompt('Hi, thanks for visiting! What is your name?');
alert('Welcome ' + userName + ', nice to meet you! Time to play a guessing game about me!');
console.log('The user name is ' + userName + '.');

// Here come the 5 questions
var response1 = prompt('Do I have 3 cats?').toUpperCase();
var answer1 = 'YES';

if (response1 === answer1 || response1 === answer1[0]) {
  alert('Nice work, ' + userName + ', you are correct!!!');
  console.log('Right answer1');
} else {
  alert('Sorry, ' + userName + ', you got it wrong!!!');
  console.log('wrong answer1');
}

var response2 = prompt('Am I from the East coast?').toUpperCase();
var answer2 = 'NO';

if (response2 === answer2 || response2 === answer2[0]) {
  alert('Good work, ' + userName + ', you guessed correctly that I am not from the East coast.');
  console.log('right answer2');
} else {
  alert('Sorry, ' + userName + ', I am actually from the West coast.');
  console.log('wrong answer2');
}

var response3 = prompt('Ok, ' + userName + ', can you tell me if I am married?').toUpperCase();
var answer3 = 'YES';

if (response3 === answer3 || response3 === answer3[0]) {
  alert(userName + ', that is correct. I am actually married to my middleschool sweetheart.');
  console.log('right answer3');
} else {
  alert('Sorry, ' + userName + ', but I really AM married.');
  console.log('wrong answer3');
}

var response4 = prompt('So, ' + userName + ', can you tell me if I am a master JS programmer?').toUpperCase();
var answer4 = 'NO';

if (response4 === answer4 || response4 === answer4[0]) {
  alert('Correct, ' + userName + ', I am still just a beginner, but well on my way to greatness!');
  console.log('right answer4');
} else {
  alert('Sorry, ' + userName + ', that was wrong. Can\'t you tell I am just a beginner?');
  console.log('wrong answer4');
}

var response5 = prompt('Final question, ' + userName + ', does the fate of the world hang in the balance?').toUpperCase();
var answer5 = 'YES';

if (response5 === answer5 || response5 === answer5[0]) {
  alert('That is correct, ' + userName + ', the very fabric of reality will rests upon the rain-slick precipice of doom!');
  console.log('right answer5');
} else {
  alert('How wrong you are, ' + userName + '. I guess you will never realize just how important JavaScript programming really is.');
  console.log('wrong answer5');
}
<commit_msg>adds question 6 to app.js too high too low<commit_after>// Here we take the user's name as input to personalize the game
var userName = prompt('Hi, thanks for visiting! What is your name?');
alert('Welcome ' + userName + ', nice to meet you! Time to play a guessing game about me!');
console.log('The user name is ' + userName + '.');

// Here come the 5 questions
var response1 = prompt('Do I have 3 cats?').toUpperCase();
var answer1 = 'YES';

if (response1 === answer1 || response1 === answer1[0]) {
  alert('Nice work, ' + userName + ', you are correct!!!');
  console.log('Right answer1');
} else {
  alert('Sorry, ' + userName + ', you got it wrong!!!');
  console.log('wrong answer1');
}

var response2 = prompt('Am I from the East coast?').toUpperCase();
var answer2 = 'NO';

if (response2 === answer2 || response2 === answer2[0]) {
  alert('Good work, ' + userName + ', you guessed correctly that I am not from the East coast.');
  console.log('right answer2');
} else {
  alert('Sorry, ' + userName + ', I am actually from the West coast.');
  console.log('wrong answer2');
}

var response3 = prompt('Ok, ' + userName + ', can you tell me if I am married?').toUpperCase();
var answer3 = 'YES';

if (response3 === answer3 || response3 === answer3[0]) {
  alert(userName + ', that is correct. I am actually married to my middleschool sweetheart.');
  console.log('right answer3');
} else {
  alert('Sorry, ' + userName + ', but I really AM married.');
  console.log('wrong answer3');
}

var response4 = prompt('So, ' + userName + ', can you tell me if I am a master JS programmer?').toUpperCase();
var answer4 = 'NO';

if (response4 === answer4 || response4 === answer4[0]) {
  alert('Correct, ' + userName + ', I am still just a beginner, but well on my way to greatness!');
  console.log('right answer4');
} else {
  alert('Sorry, ' + userName + ', that was wrong. Can\'t you tell I am just a beginner?');
  console.log('wrong answer4');
}

var response5 = prompt('Final question, ' + userName + ', does the fate of the world hang in the balance?').toUpperCase();
var answer5 = 'YES';

if (response5 === answer5 || response5 === answer5[0]) {
  alert('That is correct, ' + userName + ', the very fabric of reality will rests upon the rain-slick precipice of doom!');
  console.log('right answer5');
} else {
  alert('How wrong you are, ' + userName + '. I guess you will never realize just how important JavaScript programming really is.');
  console.log('wrong answer5');
}

// Question 6 "Too high/low w/ 4 chances and alert of remaining chances"

var chances = 4;
var answer6 = 4;

while (chances > 0) {
  var response6 = parseInt(prompt('Ok, ' + userName + ', here is a tough one. How many years have I been married? (YOU CURRENTLY HAVE ' + chances + ' TRIES TO GUESS CORRECTLY - HINT: THE ANSWER IS MORE THAN ZERO AND LESS THAN TEN)'));
  console.log(response6);
  if (response6 === answer6) {
    alert('You got it right, ' + userName + '! George has been married to his wife, Kelly, for 4 magical years.');
    console.log('The user guessed correctly');
    chances = 0;
  } else if ((chances > 0) && (response6 < answer6)) {
    chances--;
    alert('Sorry, ' + userName + ', too low. Guess again! You currently have ' + chances + ' remaining.');
    console.log('The user guessed too low');
  } else if ((chances > 0) && (response6 > answer6)) {
    chances--;
    alert('Sorry, ' + userName + ', too high. Guess again! You currently have ' + chances + ' remaining.');
    console.log('The user guessed too high');
  } else if (chances === 0) {
    alert('Looks like you ran out of guesses, ' + userName + '! Try again next time, ok?');
    console.log('The user ran out of guesses');
  } else {
    chances--;
    alert('Sorry, ' + userName + ', no sense in wasting your guesses. Should have entered a number! You now have ' + chances + ' remaining.');
    console.log('The user\'s entry was NaN');
  }
}
<|endoftext|>


<commit_before>var process = require("process");
var core = new(require("./core.js")).init;

// handle exceptions by trying to save shit and then exiting out
// just hope that its not the saving that is causing the exception to be thrown
process.on("uncaughtException", function(err) {
  console.log("Exception: " + err);
  core.emit("save");
  process.exit(1);
});

process.on("SIGINT", function() {
  console.log("Caught SIGINT, saving and exiting");
  core.emit("save");
  process.exit(1);
});

// set up auto-saving of plugin state every two minutes
setInterval(function() {
  core.emit("save");
}, 1000 * 60 * 2 );

// bail when banned
core.on("BANNED", function() {
  throw "Banned, exiting";
});

// handle auto-reconnections
core.on("disconnected", function() {
  // just connect at once, not even throttling
  process.nextTick(function() {
    core.emit("connect");
  });
});
<commit_msg>log whole stack<commit_after>var process = require("process");
var core = new(require("./core.js")).init;

// handle exceptions by trying to save shit and then exiting out
// just hope that its not the saving that is causing the exception to be thrown
process.on("uncaughtException", function(err) {

  console.log("Exception: ");
  console.log(err.stack)
  core.emit("save");
  process.exit(1);
});

process.on("SIGINT", function() {
  console.log("Caught SIGINT, saving and exiting");
  core.emit("save");
  process.exit(1);
});

// set up auto-saving of plugin state every two minutes
setInterval(function() {
  core.emit("save");
}, 1000 * 60 * 2 );

// bail when banned
core.on("BANNED", function() {
  throw "Banned, exiting";
});

// handle auto-reconnections
core.on("disconnected", function() {
  // just connect at once, not even throttling
  process.nextTick(function() {
    core.emit("connect");
  });
});
<|endoftext|>


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

var express       = require('express')
  , routes        = require('./routes')
  , path          = require('path')
  , http          = require('http')
  , _             = require('underscore')
  , jade_browser  = require('jade-browser')
  ;

/* Create the server */
var app = express()
  , server = http.createServer(app)
  ;

/* JUST in case mongo's being used.... */

/* Connect to the database */
/*
var MONGO_SERVER = 'localhost'
  , MONGO_DB_NAME = 'backbone'

mongoose.connect('mongodb://' + MONGO_SERVER + '/' + MONGO_DB_NAME, { server : { poolSize : 3 } });
mongoose.connection.on('error', function(err) {
  console.log(err);
});
*/

// Configuration
app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

// Wire up our client side templates.
// This will basically package all of our templates up in a single .js file.
// On the client, we can then render those templates whenever we need.
app.use(jade_browser('/js/templates.js', '**', {root: __dirname + '/public/js/templates', minify: true}));

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Socket.io
var io = require('socket.io').listen(server);

/**
 * our socket transport events
 *
 * You will notice that when we emit the changes
 * in `create`, `update`, and `delete` we both
 * socket.emit and socket.broadcast.emit
 *
 * socket.emit sends the changes to the browser session
 * that made the request. not required in some scenarios
 * where you are only using ioSync for Socket.io
 *
 * socket.broadcast.emit sends the changes to
 * all other browser sessions. this keeps all
 * of the pages in mirror. our client-side model
 * and collection ioBinds will pick up these events
 */
var nextId = 0;
var items = [];

io.sockets.on('connection', function (socket) {

  socket.on('items:create', function (data, callback) {
    /* do something to 'create' the item */
    console.log('CREATE ITEM', data)

    var item = { text: data.text, id: nextId++ };
    items.push(item);

    // echo the response
    callback(null, item)
    socket.broadcast.emit('items:create', item);
    socket.emit('items:create', item);
  });

  socket.on('items:read', function (data, callback) {
    /* do something to 'read' the whatever */
    if(data && data.id) {
      callback(null, _.findWhere(items, { id: data.id }));
    }
    else {
      callback(null, items)
    }
  });

  socket.on('items:update', function (data, callback) {
    var item = _.findWhere(items, { id: data.id })
    item.text = data.text;
    socket.broadcast.emit('items/' + data.id + ':update', item);
    callback(null, item);
  });

  socket.on('items:patch', function (data, callback) {
    var item = _.findWhere(items, { id: data.id })
    item.text = data.text;
    socket.broadcast.emit('items/' + data.id + ':update', item);
    callback(null, item);
  });

  socket.on('items:delete', function (data, callback) {
    items = _.reject(items, function(i) { return i.id == data.id });
    socket.broadcast.emit('items/' + data.id + ':delete', {id: data.id});
    socket.emit('items/' + data.id + ':delete', {id: data.id});
    callback(null, {id: data.id});
  });

});

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

if (!module.parent) {
  server.listen(3000);
  console.log("Realtime nodejs socket.io boilerplate", app.settings.env);
}
<commit_msg>REDIS tile storage (not working)<commit_after>/**
 * Module dependencies.
 */

var express       = require('express')
  , routes        = require('./routes')
  , path          = require('path')
  , http          = require('http')
  , _             = require('underscore')
  , jade_browser  = require('jade-browser')
  , redis         = require('redis')
  , async         = require('async')
  , client        = redis.createClient()
  ;

/* Create the server */
var app = express()
  , server = http.createServer(app)
  ;

// Configuration
app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

// Wire up our client side templates.
// This will basically package all of our templates up in a single .js file.
// On the client, we can then render those templates whenever we need.
app.use(jade_browser('/js/templates.js', '**', {root: __dirname + '/public/js/templates', minify: true}));

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Socket.io
var io = require('socket.io').listen(server);

/**
 * our socket transport events
 *
 * You will notice that when we emit the changes
 * in `create`, `update`, and `delete` we both
 * socket.emit and socket.broadcast.emit
 *
 * socket.emit sends the changes to the browser session
 * that made the request. not required in some scenarios
 * where you are only using ioSync for Socket.io
 *
 * socket.broadcast.emit sends the changes to
 * all other browser sessions. this keeps all
 * of the pages in mirror. our client-side model
 * and collection ioBinds will pick up these events
 */

var TILE_SIZE = 32;

io.sockets.on('connection', function (socket) {

  socket.on('tiles:create', function (data, callback) {
    // find a tile that is not taken,
    // mark it as taken,
    // return it back to the client.

    var multi = redis_client.multi();
    multi.get('NEXT_FREE_TILE_X');
    multi.get('NEXT_FREE_TILE_Y');
    multi.exec(function(err, values) {
      if(err)
        return console.error(err);

      var x = values[0];
      var y = values[1];

      var tile_data = [];
      for(var i = 0; i < TILE_SIZE * TILE_SIZE * 4; i++)
        tile_data.push(255);

      redis_client.hset('TILE_DATA', x + '_' + y, tile_data, function(err) {
        if(err)
          console.error(err);
      })

      chooseNextFreeTile(x,y);

      // echo the response
      callback(null, {x: x, y: y})
      socket.broadcast.emit('tiles:create', {x: x, y: y});
      socket.emit('tiles:create', {x: x, y: y});
    })

  });

  socket.on('tiles:read', function (data, callback) {
    /* do something to 'read' the whatever */
    if(data && data.tile) {
      redis_client.hget('TILE_DATA', data.id, function(err, result) {
        callback(null, {
          id: data.id
        , tileData: result
        });
      })
    }
    else {
      redis_client.hgetall('TILE_DATA', function(err, fieldvalues) {
        var tiles = [];
        for(var i = 0; i < fieldvalues.length; i+=2) {
          var t = {}
          t.id = fieldValues[i];
          t.tileData = fieldValues[i+1];
          tiles.push(t);
        }
        callback(null, tiles);
      })
    }
  });

  socket.on('tiles:update', function (data, callback) {
    redis_client.hget('TILE_DATA', data.id, function(err, result) {

      if(!result)
        return console.error('NO SUCH TILE, ', data.id)
      // need to update the tile pixel.
      var xy = data.id.split('_');
      var x = xy[0];
      var y = xy[1];
      result[y * TILE_SIZE + x]       = data.pixel[0];
      result[y * TILE_SIZE + x + 1]   = data.pixel[1];
      result[y * TILE_SIZE + x + 2]   = data.pixel[2];
      result[y * TILE_SIZE + x + 3]   = data.pixel[3];

      redis_client.hset('TILE_DATA', data.id, result, function(err) {
        if(err)
          return console.error('failed to set tile ', data.id)

        socket.broadcast.emit('tiles/' + data.id + ':update', {id: data.id, tileData: result});
        callback(null, {id: data.id});
      })
    })
  });
});

function chooseNextTile(x, y) {
  // try to keep to the center.
  if(x > 25)
    dirX = [-1, 0, 1];
  else
    dirX = [1, 0, -1];

  if(y > 25)
    dirY = [-1, 0, 1];
  else
    dirY = [1, 0, -1];

  var multi = redis_client.multi();

  for (var i = dirX.length - 1; i >= 0; i--) {
    for (var j = dirY.length - 1; j >= 0; j--) {
      multi.hexists('TILE_DATA', (x + dirX[i]) + '_' + (y + dirY[j]));
    };
  };

  multi.exec(function(err, results) {
    if(err)
      return console.error(err);
    var n = 0;
    for (var i = dirX.length - 1; i >= 0; i--) {
      for (var j = dirY.length - 1; j >= 0; j--) {
        n++;
        if(!results[n]) {

          var multi2 = redis_client.multi();
          multi2.set('NEXT_FREE_TILE_X', x + dirX[i])
          multi2.set('NEXT_FREE_TILE_Y', y + dirY[j])
          multi.exec(function(){})
        }
      };
    };
  })

}

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

redis_client.get('NEXT_FREE_TILE_X', function(err, value) {
  if(!value) {
    var multi = redis_client.multi();
    multi.set('NEXT_FREE_TILE_X', '25')
    multi.set('NEXT_FREE_TILE_Y', '25')
  }
})

if (!module.parent) {
  server.listen(3000);
  console.log("Q - Collaborative Pixel Art", app.settings.env);
}
<|endoftext|>


<commit_before>/**
 * Main file
 * Pokemon Showdown - http://pokemonshowdown.com/
 *
 * This is the main Pokemon Showdown app, and the file you should be
 * running to start Pokemon Showdown if you're using it normally.
 *
 * This file sets up our SockJS server, which handles communication
 * between users and your server, and also sets up globals. You can
 * see details in their corresponding files, but here's an overview:
 *
 * Users - from users.js
 *
 *   Most of the communication with users happens in users.js, we just
 *   forward messages between the sockets.js and users.js.
 *
 * Rooms - from rooms.js
 *
 *   Every chat room and battle is a room, and what they do is done in
 *   rooms.js. There's also a global room which every user is in, and
 *   handles miscellaneous things like welcoming the user.
 *
 * Tools - from tools.js
 *
 *   Handles getting data about Pokemon, items, etc.
 *
 * Ladders - from ladders.js and ladders-remote.js
 *
 *   Handles Elo rating tracking for players.
 *
 * Chat - from chat.js
 *
 *   Handles chat and parses chat commands like /me and /ban
 *
 * Sockets - from sockets.js
 *
 *   Used to abstract out network connections. sockets.js handles
 *   the actual server and connection set-up.
 *
 * @license MIT license
 */

'use strict';

const fs = require('fs');
const path = require('path');

/*********************************************************
 * Make sure we have everything set up correctly
 *********************************************************/

// Make sure our dependencies are available, and install them if they
// aren't

try {
	require.resolve('sockjs');
} catch (e) {
	if (require.main !== module) throw new Error("Dependencies unmet");

	let command = 'npm install --production';
	console.log('Installing dependencies: `' + command + '`...');
	require('child_process').spawnSync('sh', ['-c', command], {stdio: 'inherit'});
}

/*********************************************************
 * Load configuration
 *********************************************************/

try {
	require.resolve('./config/config');
} catch (err) {
	if (err.code !== 'MODULE_NOT_FOUND') throw err; // should never happen

	// Copy it over synchronously from config-example.js since it's needed before we can start the server
	console.log("config.js doesn't exist - creating one with default settings...");
	fs.writeFileSync(path.resolve(__dirname, 'config/config.js'),
		fs.readFileSync(path.resolve(__dirname, 'config/config-example.js'))
	);
} finally {
	global.Config = require('./config/config');
}

if (Config.watchconfig) {
	let configPath = require.resolve('./config/config');
	fs.watchFile(configPath, (curr, prev) => {
		if (curr.mtime <= prev.mtime) return;
		try {
			delete require.cache[configPath];
			global.Config = require('./config/config');
			if (global.Users) Users.cacheGroupData();
			console.log('Reloaded config/config.js');
		} catch (e) {
			console.log('Error reloading config/config.js: ' + e.stack);
		}
	});
}

/*********************************************************
 * Set up most of our globals
 *********************************************************/

global.sqlite3 = require('sqlite3');

global.Db = require('origindb')('config/db');

global.Monitor = require('./monitor');

global.Tools = require('./tools');
global.toId = Tools.getId;

global.LoginServer = require('./loginserver');

global.Ladders = require(Config.remoteladder ? './ladders-remote' : './ladders');

global.Users = require('./users');

global.Punishments = require('./punishments');

global.Chat = require('./chat');

global.Rooms = require('./rooms');

global.Tells = require('./tells.js');

delete process.send; // in case we're a child process
global.Verifier = require('./verifier');
Verifier.PM.spawn();

global.SG = {};

global.Simulator = require('./simulator');

global.Tournaments = require('./tournaments');

global.Dnsbl = require('./dnsbl');
Dnsbl.loadDatacenters();

if (Config.crashguard) {
	// graceful crash - allow current battles to finish before restarting
	process.on('uncaughtException', err => {
		let crashType = require('./crashlogger')(err, 'The main process');
		if (crashType === 'lockdown') {
			Rooms.global.startLockdown(err);
		} else {
			Rooms.global.reportCrash(err);
		}
	});
	process.on('unhandledRejection', err => {
		throw err;
	});
	process.on('exit', code => {
		let exitCodes = {
			1: 'Uncaught Fatal Exception',
			2: 'Misuse of shell builtins',
			3: 'Internal JavaScript Parse Error',
			4: 'Internal JavaScript Evaluation Failure',
			5: 'Fatal Error',
			6: 'Non-function Internal Exception Handler',
			7: 'Internal Exception Handler Run-Time Failure',
			8: 'Unused Error Code. Formerly used by nodejs. Sometimes indicate a uncaught exception',
			9: 'Invalid Argument',
			10: 'Internal JavaScript Run-Time Failure',
			11: 'Server Exit Code: Exiting via /eval process.exit(11);',
			12: 'Invalid Debug Argument',
			130: 'Control-C via Terminal or Command Prompt'
		};
		if (code !== 0) {
			let exitInfo = 'Unused Error Code';
			if (exitCodes[code]) {
				exitInfo = exitCodes[code];
			} else if (code > 128) exitInfo = 'Signal Exit';
			console.log('');
			console.error('WARNING: Process exiting with code ' + code);
			console.error('Exit code details: ' + exitInfo + '.');
			console.error('Refer to https://github.com/nodejs/node-v0.x-archive/blob/master/doc/api/process.markdown#exit-codes for more details. The process will now exit.');
		}
	});
}

/*********************************************************
 * Start networking processes to be connected to
 *********************************************************/

global.Sockets = require('./sockets');

exports.listen = function (port, bindAddress, workerCount) {
	Sockets.listen(port, bindAddress, workerCount);
};

if (require.main === module) {
	// if running with node app.js, set up the server directly
	// (otherwise, wait for app.listen())
	let port;
	if (process.argv[2]) {
		port = parseInt(process.argv[2]); // eslint-disable-line radix
	}
	Sockets.listen(port);
}

/*********************************************************
 * Set up our last global
 *********************************************************/

// Generate and cache the format list.
Tools.includeFormats();

global.TeamValidator = require('./team-validator');
TeamValidator.PM.spawn();

/*********************************************************
 * Start up the REPL server
 *********************************************************/

require('./repl').start('app', cmd => eval(cmd));
<commit_msg>Unrequire simulator<commit_after>/**
 * Main file
 * Pokemon Showdown - http://pokemonshowdown.com/
 *
 * This is the main Pokemon Showdown app, and the file you should be
 * running to start Pokemon Showdown if you're using it normally.
 *
 * This file sets up our SockJS server, which handles communication
 * between users and your server, and also sets up globals. You can
 * see details in their corresponding files, but here's an overview:
 *
 * Users - from users.js
 *
 *   Most of the communication with users happens in users.js, we just
 *   forward messages between the sockets.js and users.js.
 *
 * Rooms - from rooms.js
 *
 *   Every chat room and battle is a room, and what they do is done in
 *   rooms.js. There's also a global room which every user is in, and
 *   handles miscellaneous things like welcoming the user.
 *
 * Tools - from tools.js
 *
 *   Handles getting data about Pokemon, items, etc.
 *
 * Ladders - from ladders.js and ladders-remote.js
 *
 *   Handles Elo rating tracking for players.
 *
 * Chat - from chat.js
 *
 *   Handles chat and parses chat commands like /me and /ban
 *
 * Sockets - from sockets.js
 *
 *   Used to abstract out network connections. sockets.js handles
 *   the actual server and connection set-up.
 *
 * @license MIT license
 */

'use strict';

const fs = require('fs');
const path = require('path');

/*********************************************************
 * Make sure we have everything set up correctly
 *********************************************************/

// Make sure our dependencies are available, and install them if they
// aren't

try {
	require.resolve('sockjs');
} catch (e) {
	if (require.main !== module) throw new Error("Dependencies unmet");

	let command = 'npm install --production';
	console.log('Installing dependencies: `' + command + '`...');
	require('child_process').spawnSync('sh', ['-c', command], {stdio: 'inherit'});
}

/*********************************************************
 * Load configuration
 *********************************************************/

try {
	require.resolve('./config/config');
} catch (err) {
	if (err.code !== 'MODULE_NOT_FOUND') throw err; // should never happen

	// Copy it over synchronously from config-example.js since it's needed before we can start the server
	console.log("config.js doesn't exist - creating one with default settings...");
	fs.writeFileSync(path.resolve(__dirname, 'config/config.js'),
		fs.readFileSync(path.resolve(__dirname, 'config/config-example.js'))
	);
} finally {
	global.Config = require('./config/config');
}

if (Config.watchconfig) {
	let configPath = require.resolve('./config/config');
	fs.watchFile(configPath, (curr, prev) => {
		if (curr.mtime <= prev.mtime) return;
		try {
			delete require.cache[configPath];
			global.Config = require('./config/config');
			if (global.Users) Users.cacheGroupData();
			console.log('Reloaded config/config.js');
		} catch (e) {
			console.log('Error reloading config/config.js: ' + e.stack);
		}
	});
}

/*********************************************************
 * Set up most of our globals
 *********************************************************/

global.sqlite3 = require('sqlite3');

global.Db = require('origindb')('config/db');

global.Monitor = require('./monitor');

global.Tools = require('./tools');
global.toId = Tools.getId;

global.LoginServer = require('./loginserver');

global.Ladders = require(Config.remoteladder ? './ladders-remote' : './ladders');

global.Users = require('./users');

global.Punishments = require('./punishments');

global.Chat = require('./chat');

global.Rooms = require('./rooms');

global.Tells = require('./tells.js');

delete process.send; // in case we're a child process
global.Verifier = require('./verifier');
Verifier.PM.spawn();

global.SG = {};

global.Tournaments = require('./tournaments');

global.Dnsbl = require('./dnsbl');
Dnsbl.loadDatacenters();

if (Config.crashguard) {
	// graceful crash - allow current battles to finish before restarting
	process.on('uncaughtException', err => {
		let crashType = require('./crashlogger')(err, 'The main process');
		if (crashType === 'lockdown') {
			Rooms.global.startLockdown(err);
		} else {
			Rooms.global.reportCrash(err);
		}
	});
	process.on('unhandledRejection', err => {
		throw err;
	});
	process.on('exit', code => {
		let exitCodes = {
			1: 'Uncaught Fatal Exception',
			2: 'Misuse of shell builtins',
			3: 'Internal JavaScript Parse Error',
			4: 'Internal JavaScript Evaluation Failure',
			5: 'Fatal Error',
			6: 'Non-function Internal Exception Handler',
			7: 'Internal Exception Handler Run-Time Failure',
			8: 'Unused Error Code. Formerly used by nodejs. Sometimes indicate a uncaught exception',
			9: 'Invalid Argument',
			10: 'Internal JavaScript Run-Time Failure',
			11: 'Server Exit Code: Exiting via /eval process.exit(11);',
			12: 'Invalid Debug Argument',
			130: 'Control-C via Terminal or Command Prompt'
		};
		if (code !== 0) {
			let exitInfo = 'Unused Error Code';
			if (exitCodes[code]) {
				exitInfo = exitCodes[code];
			} else if (code > 128) exitInfo = 'Signal Exit';
			console.log('');
			console.error('WARNING: Process exiting with code ' + code);
			console.error('Exit code details: ' + exitInfo + '.');
			console.error('Refer to https://github.com/nodejs/node-v0.x-archive/blob/master/doc/api/process.markdown#exit-codes for more details. The process will now exit.');
		}
	});
}

/*********************************************************
 * Start networking processes to be connected to
 *********************************************************/

global.Sockets = require('./sockets');

exports.listen = function (port, bindAddress, workerCount) {
	Sockets.listen(port, bindAddress, workerCount);
};

if (require.main === module) {
	// if running with node app.js, set up the server directly
	// (otherwise, wait for app.listen())
	let port;
	if (process.argv[2]) {
		port = parseInt(process.argv[2]); // eslint-disable-line radix
	}
	Sockets.listen(port);
}

/*********************************************************
 * Set up our last global
 *********************************************************/

// Generate and cache the format list.
Tools.includeFormats();

global.TeamValidator = require('./team-validator');
TeamValidator.PM.spawn();

/*********************************************************
 * Start up the REPL server
 *********************************************************/

require('./repl').start('app', cmd => eval(cmd));
<|endoftext|>


<commit_before>var express = require('express')
  , routes = require('./routes')
  , path = require('path')
  , epics = require('epics')
  , app = express()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server);

app.configure(function(){
  app.set('port', 7000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('view options', {layout: true})
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

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

var pvs = {};

function removePV(pvName) {
  var pvInfo = pvs[pvName];
  if(pvInfo) {
    pvInfo.watchers -= 1;
    if(pvInfo.watchers === 0) {
      // TODO: Clear channel
    }
  }
}

function addPV(pvName) {
  var pvInfo = pvs[pvName];
  if(pvInfo) {
    pvInfo.watchers += 1;
  } else {
    var pv = new epics.Channel(pvName);
    pv.on('value', function(data) {
      console.log(data);
      io.sockets.emit('value', {pvName: pv.pvName, value:  data});
    });
    pv.connect(function(err) {
      console.log('connect:', err);
      if(!err) {
        pv.monitor();
      }
    });
    pvs[pvName] = {
      watchers: 1,
      pv: pv
    };
  }
}

io.sockets.on('connection', function(socket) {
  socket.on('change pv name', function(data) {
    removePV(data['prevPVName']);
    addPV(data['newPVName']);
  });
});

server.listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});
<commit_msg>Disconnect channel when no-one is observing PV<commit_after>var express = require('express')
  , routes = require('./routes')
  , path = require('path')
  , epics = require('epics')
  , app = express()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server, {'log level': 1});

app.configure(function(){
  app.set('port', 7000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('view options', {layout: true})
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

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

var pvs = {};

function removePV(pvName) {
  var pvInfo = pvs[pvName];
  if(pvInfo) {
    pvInfo.watchers -= 1;
    if(pvInfo.watchers === 0) {
      pvInfo.pv.disconnect();
      delete pvs[pvName];
    }
  }
}

function addPV(pvName) {
  var pvInfo = pvs[pvName];
  if(pvInfo) {
    pvInfo.watchers += 1;
  } else {
    var pv = new epics.Channel(pvName);
    pv.on('value', function(data) {
      console.log(data);
      io.sockets.emit('value', {pvName: pv.pvName, value:  data});
    });
    pv.connect(function(err) {
      console.log('connect:', err);
      if(!err) {
        pv.monitor();
      }
    });
    pvs[pvName] = {
      watchers: 1,
      pv: pv
    };
  }
}

io.sockets.on('connection', function(socket) {
  socket.on('change pv name', function(data) {
    removePV(data['prevPVName']);
    addPV(data['newPVName']);
  });
});

server.listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('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 routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

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

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

app.use('/', routes);
app.use('/users', users);

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

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

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

module.exports = app;
<commit_msg>Add MongoDb connect into app<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 routes = require('./routes/index');
var users = require('./routes/users');

var app = express();
var MongoClient = require('mongodb');

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

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

app.use('/', routes);
app.use('/users', users);

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

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

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

module.exports = app;
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const os = require('os');
const Table = require('cli-table');
const thegamesdb = require('thegamesdb');
const gcdb = require('gamecollection-mongodb');
const labels = require('./labels');
const utils = require('./utils');

module.exports = {
	getCollection: async () => {
		const gamecollection = await gcdb.getGames();

		let table = new Table({
			head: labels.collectionTableHeader,
			colWidths: [60, 40]
		});

		for (const game of gamecollection) {
			table.push([game.title, game.platform]);
		}

		console.log(table.toString());
		utils.calculateGames(gamecollection);
	},
	getCollectionPerPlatform: async () => {
		const gamecollectionPerPlatform = await gcdb.getGamesPerPlatform();
		let table;

		for (const gamesPerPlatform of gamecollectionPerPlatform) {
			table = new Table({
				head: [gamesPerPlatform.platform],
				colWidths: [100]
			});

			for (const game of gamesPerPlatform.games) {
				table.push([game.title]);
			}
			table.push([labels.calculateGames(gamesPerPlatform.games.length)]);
			console.log(table.toString());
		}
	},
	addGame: async (game) => {
		const thegamesdbResult = await thegamesdb.getGamesList({
			name: game
		});

		if (thegamesdbResult.length) {
			const choices = thegamesdbResult.map(item => {
				return {
					name: `${item.title} | ${item.platform}`,
					value: item.id
				};
			});

			const addGamesDialog = await utils.dialog('checkbox', labels.dialog.add.title, 'gameIDs', choices, 10, labels.dialog.add.validationMessage);
			const addGamesConfirmDialog = await utils.dialog('confirm', labels.dialog.add.comfirmTitle, 'isAdding');

			if (addGamesConfirmDialog.isAdding) {
				for (const gameID of addGamesDialog.gameIDs) {
					let gameInformation = await thegamesdb.getGame({ id: gameID });
					await gcdb.addGame(gameInformation);
					utils.gameAdded(gameInformation.title);
				}
			}
		}
		else {
			utils.console('log', labels.warning.noGamesFound);
		}
	},
	removeGame: async (game) => {
		const query = {
			title: game
		};

		const filteredGames = await gcdb.getGames(query);

		if (filteredGames.length) {
			const choices = filteredGames.map(item => {
				return {
					name: `${item.title} | ${item.platform}`,
					value: item._id
				};
			});

			const removeGamesDialog = await utils.dialog('checkbox', labels.dialog.remove.title, 'removeGame', choices, 10, labels.dialog.remove.validationMessage);
			const removeGamesConfirmDialog = await utils.dialog('confirm', labels.dialog.remove.comfirmTitle, 'isRemoving');

			if (removeGamesConfirmDialog.isRemoving) {
				for (const gameID of removeGamesDialog.removeGame) {
					let gameToBeRemoved = await gcdb.getGame(gameID);
					await gcdb.deleteGame(gameID);
					utils.gameRemoved(gameToBeRemoved.title);
				}
			}
		}
		else {
			utils.console('log', labels.warning.noGamesFound);
		}
	},
	repair: async () => {
		const failedGames = [];
		const apiField = 'apiId';
		const gamecollection = await gcdb.getGames();
		const gameCollectionWithoutID = gamecollection.filter(currentValue => {
			return !currentValue.hasOwnProperty(apiField);
		});

		if (gameCollectionWithoutID.length) {
			utils.console('log', labels.repair.progress);

			for (const game of gameCollectionWithoutID) {
				const gamelist = await thegamesdb.getGamesList({ name: game.title, platform: game.platform });
				const matchedGame = utils.getMatchedGame(game, gamelist);

				if (matchedGame !== null) {
					await gcdb.updateGame(game._id, apiField, { thegamesdb: matchedGame.id });
				}
				else {
					failedGames.push(game);
				}
			}

			if (failedGames.length) {
				for (const failedGame of failedGames) {
					await gcdb.deleteGame(failedGame._id);
					utils.gameRemoved(failedGame.title);
					utils.console('log', labels.repair.addFailedGame(failedGame));
					await module.exports.addGame(failedGame.title);
				}
			}

			utils.console('log', labels.repair.complete);
		}
		else {
			utils.console('log', labels.repair.noGamesToRepair);
		}
	},
	export: async () => {
		const path = os.homedir() + '/gamecollection.json';

		try {
			const gamecollection = await gcdb.getGames();
			fs.writeFileSync(path, JSON.stringify(gamecollection));
			utils.console('success', labels.export.successfullyExported());
		}
		catch (err) {
			utils.console('error', labels.export.failed);
			throw err;
		}
	},
	import: async () => {
		const path = os.homedir() + '/gamecollection.json';

		try {
			const gamecollectionFromFile = fs.readFileSync(path, 'utf-8');
			const importConfirmDialog = await utils.dialog('confirm', labels.dialog.import.confirmTitle, 'isImporting');

			if (importConfirmDialog.isImporting) {
				await gcdb.dropGamecollection();
				for (const game of JSON.parse(gamecollectionFromFile)) {
					await gcdb.addGame(game);
					utils.gameAdded(game.title);
				}
			}
		}
		catch (err) {
			throw err;
		}
	}
};
<commit_msg>Added regex to get all the games form the collectoin which matches the criteria<commit_after>'use strict';

const fs = require('fs');
const os = require('os');
const Table = require('cli-table');
const thegamesdb = require('thegamesdb');
const gcdb = require('gamecollection-mongodb');
const labels = require('./labels');
const utils = require('./utils');

module.exports = {
	getCollection: async () => {
		const gamecollection = await gcdb.getGames();

		let table = new Table({
			head: labels.collectionTableHeader,
			colWidths: [60, 40]
		});

		for (const game of gamecollection) {
			table.push([game.title, game.platform]);
		}

		console.log(table.toString());
		utils.calculateGames(gamecollection);
	},
	getCollectionPerPlatform: async () => {
		const gamecollectionPerPlatform = await gcdb.getGamesPerPlatform();
		let table;

		for (const gamesPerPlatform of gamecollectionPerPlatform) {
			table = new Table({
				head: [gamesPerPlatform.platform],
				colWidths: [100]
			});

			for (const game of gamesPerPlatform.games) {
				table.push([game.title]);
			}
			table.push([labels.calculateGames(gamesPerPlatform.games.length)]);
			console.log(table.toString());
		}
	},
	addGame: async (game) => {
		const thegamesdbResult = await thegamesdb.getGamesList({
			name: game
		});

		if (thegamesdbResult.length) {
			const choices = thegamesdbResult.map(item => {
				return {
					name: `${item.title} | ${item.platform}`,
					value: item.id
				};
			});

			const addGamesDialog = await utils.dialog('checkbox', labels.dialog.add.title, 'gameIDs', choices, 10, labels.dialog.add.validationMessage);
			const addGamesConfirmDialog = await utils.dialog('confirm', labels.dialog.add.comfirmTitle, 'isAdding');

			if (addGamesConfirmDialog.isAdding) {
				for (const gameID of addGamesDialog.gameIDs) {
					let gameInformation = await thegamesdb.getGame({ id: gameID });
					await gcdb.addGame(gameInformation);
					utils.gameAdded(gameInformation.title);
				}
			}
		}
		else {
			utils.console('log', labels.warning.noGamesFound);
		}
	},
	removeGame: async (game) => {
		const regexp = RegExp(game);
		const gamecollection = await gcdb.getGames();

		const potentialGamesToRemove = gamecollection.filter(currentValue => {
			return regexp.test(currentValue.title);
		});

		if (potentialGamesToRemove.length) {
			const choices = potentialGamesToRemove.map(item => {
				return {
					name: `${item.title} | ${item.platform}`,
					value: item._id
				};
			});

			const removeGamesDialog = await utils.dialog('checkbox', labels.dialog.remove.title, 'removeGame', choices, 10, labels.dialog.remove.validationMessage);
			const removeGamesConfirmDialog = await utils.dialog('confirm', labels.dialog.remove.comfirmTitle, 'isRemoving');

			if (removeGamesConfirmDialog.isRemoving) {
				for (const gameID of removeGamesDialog.removeGame) {
					let gameToBeRemoved = await gcdb.getGame(gameID);
					await gcdb.deleteGame(gameID);
					utils.gameRemoved(gameToBeRemoved.title);
				}
			}
		}
		else {
			utils.console('log', labels.warning.noGamesFound);
		}
	},
	repair: async () => {
		const failedGames = [];
		const apiField = 'apiId';
		const gamecollection = await gcdb.getGames();
		const gameCollectionWithoutID = gamecollection.filter(currentValue => {
			return !currentValue.hasOwnProperty(apiField);
		});

		if (gameCollectionWithoutID.length) {
			utils.console('log', labels.repair.progress);

			for (const game of gameCollectionWithoutID) {
				const gamelist = await thegamesdb.getGamesList({ name: game.title, platform: game.platform });
				const matchedGame = utils.getMatchedGame(game, gamelist);

				if (matchedGame !== null) {
					await gcdb.updateGame(game._id, apiField, { thegamesdb: matchedGame.id });
				}
				else {
					failedGames.push(game);
				}
			}

			if (failedGames.length) {
				for (const failedGame of failedGames) {
					await gcdb.deleteGame(failedGame._id);
					utils.gameRemoved(failedGame.title);
					utils.console('log', labels.repair.addFailedGame(failedGame));
					await module.exports.addGame(failedGame.title);
				}
			}

			utils.console('log', labels.repair.complete);
		}
		else {
			utils.console('log', labels.repair.noGamesToRepair);
		}
	},
	export: async () => {
		const path = os.homedir() + '/gamecollection.json';

		try {
			const gamecollection = await gcdb.getGames();
			fs.writeFileSync(path, JSON.stringify(gamecollection));
			utils.console('success', labels.export.successfullyExported());
		}
		catch (err) {
			utils.console('error', labels.export.failed);
			throw err;
		}
	},
	import: async () => {
		const path = os.homedir() + '/gamecollection.json';

		try {
			const gamecollectionFromFile = fs.readFileSync(path, 'utf-8');
			const importConfirmDialog = await utils.dialog('confirm', labels.dialog.import.confirmTitle, 'isImporting');

			if (importConfirmDialog.isImporting) {
				await gcdb.dropGamecollection();
				for (const game of JSON.parse(gamecollectionFromFile)) {
					await gcdb.addGame(game);
					utils.gameAdded(game.title);
				}
			}
		}
		catch (err) {
			throw err;
		}
	}
};
<|endoftext|>


<commit_before>'use strict';
//scafolding//1.Event listner for Image.//2.constructor for image /product objects.//a.path to image file.//b.image name.
//c.vote property.
//1.Event listner for Image.
//2.constructor for image /product objects.
//a.path to image file.
//b.image name.
//c.vote property.

//var counter = 0;  //click counter set to 0
var round = function(number, precision) {
  return parseFloat(number.toFixed(precision));
};
// var randomInteger = function(min, max) {
//   return Math.floor(Math.random() * (max - min + 1) + min);
// };20 pictures with index 0 to 19
function randomInteger () {
  return round((Math.floor(Math.random() * 20) + 0),0);
}
//var imgName = ['bag','banana','bathroom','boots','breakfast','bubblegum','chair',
//'cthulhu','dog-duck','dragon','pen','pet-sweep','scissors','shark','sweep','tauntaun','unicorn','usb','water-can','wine-glass',];
//var filepath = ['img/bag.jpg','img/banana.jpg','img/bathroom.jpg','img/boots.jpg','img/breakfast.jpg','img/bubblegum.jpg','img/chair.jpg',
//'img/cthulhu.jpg','img/dog-duck.jpg','img/dragon.jpg','img/pen.jpg','img/pet-sweep.jpg','img/scissors.jpg','img/shark.jpg','img/sweep.jng','img/tauntaun.jpg','img/unicorn.jpg','img/usb.jpg','img/water-can.jpg','img/wine-glass.jpg',];

var allImages = []; //1. Create empty array
//The following code creates a prototype,'Image', and an object of that type, the 'Image'.
//The code then displays the constructor property for the object 'Image'.
//All objects in JavaScript are descended from Object;
//all objects inherit methods and properties from 'Object.prototype'.

function Image (filepath, imgName,votes) {   //2. Constructor : Needs to be capital letter
  this.imgName = imgName;
  this.filepath = filepath;
  this.howmanytimesVoted = 0;
  allImages.push(this);
}
//Image.prototype.clickedImage
//3. Then create Object instances
Image.prototype.numberOftimesTheImageClicked = function() {
  for (var i = 0; i < 15; i++) {
    this.howmanytimesVoted;
  }
};

Image.prototype.callAllMethods = function() {
  this.numberOftimesTheImageClicked();
};

new Image ('img/bag.jpg', 'bag');
new Image ('img/banana.jpg', 'banana');
new Image ('img/bathroom.jpg', 'bathroom');
new Image ('img/boots.jpg', 'boots');
new Image ('img/breakfast.jpg', 'breakfast');
new Image ('img/bubblegum.jpg', 'bubblegum');
new Image ( 'img/chair.jpg', 'chair');
new Image ('img/cthulhu.jpg', 'cthulhu');
new Image ('img/dog-duck.jpg', 'dog-duck');
new Image ('img/dragon.jpg', 'dragon');
new Image ('img/pen.jpg', 'pen');
new Image ('img/pet-sweep.jpg', 'pet-sweep');
new Image ('img/scissors.jpg', 'scissors');
new Image ('img/shark.jpg', 'shark');
new Image('img/sweep.jng','sweep');
new Image ('img/tauntaun.jpg', 'tauntaun');
new Image ('img/unicorn.jpg', 'unicorn');
new Image ('img/usb.jpg', 'usb');
new Image ('img/water-can.jpg', 'water-can');
new Image ('img/wine-glass.jpg', 'wine-glass');

function makeItAllHappen() {
  for (var i = 0; i < allImages.length; i++) {
    allImages[i].callAllMethods();
  }
}
makeItAllHappen();

//Object litral
var productImage = {
  name: 'image Name',
  numberOfClicksOnTheImage: 0,
};

productImage.nameOftheImage = function() {
  for (var i = 0; i < allImages.length; i++) {
    this.dailyTotalBeans += allImages[i].totalBeansPerDay;
  }
};

function productImageAllMethods() {
  productImage.nameOftheImage();
  //all methods here.
}
productImageAllMethods();

//Rendering a table is building the HTML page in javascript and then inserted it into the DOM.
// Document object Model specifies the browser should create a model of an HTML page and how javascript can access
// and update the contents of a web page while it is in the browser window.

//4. Now Access -- function that displays the pictures on page
var pictureOne = allImages[randomInteger()]; //pulling the random number in
var leftImg = document.getElementById('left');
leftImg.src = pictureOne.filepath;
leftImg.alt = pictureOne.imgName;

var pictureTwo = allImages[randomInteger()];
var centerImg = document.getElementById('center');
centerImg.src = pictureTwo.filepath;
centerImg.alt = pictureTwo.imgName;

var pictureThree = allImages[randomInteger()];
var rightImg = document.getElementById('right');
rightImg.src = pictureThree.filepath;
rightImg.alt = pictureThree.imgName;
//Avoid duplication of images.
function displayImage (){   //4. Now Access -- function that displays the pictures on page
  //don't show any duplicate code!
  var displayImageArray = [];
  var leftPicture = randomInteger();
  while (leftPicture === displayImageArray[0] || leftPicture === displayImageArray[1] || leftPicture === displayImageArray[2])
  {
    leftPicture = randomInteger();//This is index.

  }
  leftImg.src = allImages[leftPicture].filepath;

  var centerPicture = randomInteger();
  while (centerPicture === displayImageArray[0] || centerPicture === displayImageArray[1] || centerPicture === displayImageArray[2] || centerPicture === leftPicture)

  {
    centerPicture = randomInteger();//This is index.
  }
  centerImg.src = allImages[centerPicture].filepath;

  var rightPicture = randomInteger();
  while (rightPicture === displayImageArray[0] || rightPicture === displayImageArray[1] || rightPicture === displayImageArray[2]
    || rightPicture === leftPicture || rightPicture === centerPicture)

    {
    rightPicture = randomInteger();//This is index.
  }
  rightImg.src = allImages[rightPicture].filepath;
  displayImageArray.push(leftPicture,centerPicture,rightPicture);
}
displayImage();

var rotateImages = document.getElementById('wrapper');
rotateImages.addEventListener('click',changeThePicturesShown);
function changeThePicturesShown(event){
  if (event.target.id === 'wrapper'){
    alert('Please click on an image.');
  }
  for (var i = 0; i <= 15; i++) {
    if(event.target.alt === allImages[i].imgName) {
      allImages[i].votes += 1;
      displayImage();
    }
  }
}
<commit_msg>Adding the click and changing images<commit_after>'use strict';
//scafolding//1.Event listner for Image.//2.constructor for image /product objects.//a.path to image file.//b.image name.
//c.vote property.
//1.Event listner for Image.
//2.constructor for image /product objects.
//a.path to image file.
//b.image name.
//c.vote property.

//var counter = 0;  //click counter set to 0
var round = function(number, precision) {
  return parseFloat(number.toFixed(precision));
};
// var randomInteger = function(min, max) {
//   return Math.floor(Math.random() * (max - min + 1) + min);
// };20 pictures with index 0 to 19
function randomInteger () {
  return round((Math.floor(Math.random() * 20) + 0),0);
}
//var imgName = ['bag','banana','bathroom','boots','breakfast','bubblegum','chair',
//'cthulhu','dog-duck','dragon','pen','pet-sweep','scissors','shark','sweep','tauntaun','unicorn','usb','water-can','wine-glass',];
//var filepath = ['img/bag.jpg','img/banana.jpg','img/bathroom.jpg','img/boots.jpg','img/breakfast.jpg','img/bubblegum.jpg','img/chair.jpg',
//'img/cthulhu.jpg','img/dog-duck.jpg','img/dragon.jpg','img/pen.jpg','img/pet-sweep.jpg','img/scissors.jpg','img/shark.jpg','img/sweep.jng','img/tauntaun.jpg','img/unicorn.jpg','img/usb.jpg','img/water-can.jpg','img/wine-glass.jpg',];

var allImages = []; //1. Create empty array
//The following code creates a prototype,'Image', and an object of that type, the 'Image'.
//The code then displays the constructor property for the object 'Image'.
//All objects in JavaScript are descended from Object;
//all objects inherit methods and properties from 'Object.prototype'.

function Image (filepath, imgName,votes) {   //2. Constructor : Needs to be capital letter
  this.imgName = imgName;
  this.filepath = filepath;
  this.howmanytimesVoted = 0;
  allImages.push(this);
}
//Image.prototype.clickedImage
//3. Then create Object instances
Image.prototype.numberOftimesTheImageClicked = function() {
  for (var i = 0; i < 15; i++) {
    this.howmanytimesVoted;
  }
};

Image.prototype.callAllMethods = function() {
  this.numberOftimesTheImageClicked();
};

new Image ('img/bag.jpg', 'bag');
new Image ('img/banana.jpg', 'banana');
new Image ('img/bathroom.jpg', 'bathroom');
new Image ('img/boots.jpg', 'boots');
new Image ('img/breakfast.jpg', 'breakfast');
new Image ('img/bubblegum.jpg', 'bubblegum');
new Image ( 'img/chair.jpg', 'chair');
new Image ('img/cthulhu.jpg', 'cthulhu');
new Image ('img/dog-duck.jpg', 'dog-duck');
new Image ('img/dragon.jpg', 'dragon');
new Image ('img/pen.jpg', 'pen');
new Image ('img/pet-sweep.jpg', 'pet-sweep');
new Image ('img/scissors.jpg', 'scissors');
new Image ('img/shark.jpg', 'shark');
new Image('img/sweep.jng','sweep');
new Image ('img/tauntaun.jpg', 'tauntaun');
new Image ('img/unicorn.jpg', 'unicorn');
new Image ('img/usb.jpg', 'usb');
new Image ('img/water-can.jpg', 'water-can');
new Image ('img/wine-glass.jpg', 'wine-glass');

function makeItAllHappen() {
  for (var i = 0; i < allImages.length; i++) {
    allImages[i].callAllMethods();
  }
}
makeItAllHappen();

//Object litral
var productImage = {
  name: 'image Name',
  numberOfClicksOnTheImage: 0,
};

productImage.nameOftheImage = function() {
  for (var i = 0; i < allImages.length; i++) {
    this.dailyTotalBeans += allImages[i].totalBeansPerDay;
  }
};

function productImageAllMethods() {
  productImage.nameOftheImage();
  //all methods here.
}
productImageAllMethods();

//Rendering a table is building the HTML page in javascript and then inserted it into the DOM.
// Document object Model specifies the browser should create a model of an HTML page and how javascript can access
// and update the contents of a web page while it is in the browser window.

//4. Now Access -- function that displays the pictures on page
var pictureOne = allImages[randomInteger()]; //pulling the random number in
var leftImg = document.getElementById('left');
leftImg.src = pictureOne.filepath;
leftImg.alt = pictureOne.imgName;

var pictureTwo = allImages[randomInteger()];
var centerImg = document.getElementById('center');
centerImg.src = pictureTwo.filepath;
centerImg.alt = pictureTwo.imgName;

var pictureThree = allImages[randomInteger()];
var rightImg = document.getElementById('right');
rightImg.src = pictureThree.filepath;
rightImg.alt = pictureThree.imgName;
//Avoid duplication of images.
function displayImage (){   //4. Now Access -- function that displays the pictures on page
  //don't show any duplicate code!
  var displayImageArray = [];
  var leftPicture = randomInteger();
  while (leftPicture === displayImageArray[0] || leftPicture === displayImageArray[1] || leftPicture === displayImageArray[2])
  {
    leftPicture = randomInteger();//This is index.

  }
  leftImg.src = allImages[leftPicture].filepath;

  var centerPicture = randomInteger();
  while (centerPicture === displayImageArray[0] || centerPicture === displayImageArray[1] || centerPicture === displayImageArray[2] || centerPicture === leftPicture)

  {
    centerPicture = randomInteger();//This is index.
  }
  centerImg.src = allImages[centerPicture].filepath;

  var rightPicture = randomInteger();
  while (rightPicture === displayImageArray[0] || rightPicture === displayImageArray[1] || rightPicture === displayImageArray[2]
    || rightPicture === leftPicture || rightPicture === centerPicture)

    {
    rightPicture = randomInteger();//This is index.
  }
  rightImg.src = allImages[rightPicture].filepath;
  displayImageArray.push(leftPicture,centerPicture,rightPicture);
}
displayImage();

var rotateImages = document.getElementById('wrapper');
rotateImages.addEventListener('click',changeThePicturesShown);
function changeThePicturesShown(event){
  if (event.target.id === 'wrapper'){
    alert('Please click on an image.');
  }
  for (var i = 0; i < allImages.length; i++) {
    if(event.target.alt === allImages[i].imgName) {
      allImages[i].votes += 1;
      displayImage();
    }
  }
}
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
//var favicon = require('static-favicon');
var logger = require('morgan');
//var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//var cors = require('cors');
var mongoose = require('mongoose');

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

var Idea = require("./api/idea");
var Ideaboard = require("./api/ideaboard");
var User = require("./api/user");

mongoose.connect("mongodb://localhost/IdeaHub");

var app = module.exports = express();

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

app.use(bodyParser());
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use( bodyParser.urlencoded() ); // to support URL-encoded bodies
//app.use(cors());

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

//app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
//app.use(cookieParser());
//app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
//app.use('/users', users);

//User 操作
app.post('/user', User.newUser);
app.get('/user', User.listUser);

//Idea 操作
app.post('/idea',Idea.newIdea);
app.get('/getIp',Idea.getIp);
app.get('/idea',Idea.listIdea);

//Ideaboard 操作
app.post('/ideaboard',Ideaboard.newIdeaboard);
app.get('/ideaboard',Ideaboard.listIdeaboard);
app.get('/b/:ideaboard',Idea.listHackathonIdea);

app.get('/users', function(req, res, next) {
    //return next(error(401, 'user list is empty'));
    return res.send("test_user");
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

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

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

if (!module.parent) {
  app.listen(3009);
  console.log("Express started at 3009");
}

module.exports = app;
<commit_msg>use /api/<commit_after>var express = require('express');
var path = require('path');
//var favicon = require('static-favicon');
var logger = require('morgan');
//var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//var cors = require('cors');
var mongoose = require('mongoose');

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

var Idea = require("./api/idea");
var Ideaboard = require("./api/ideaboard");
var User = require("./api/user");

mongoose.connect("mongodb://localhost/IdeaHub");

var app = module.exports = express();

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

app.use(bodyParser());
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use( bodyParser.urlencoded() ); // to support URL-encoded bodies
//app.use(cors());

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

//app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
//app.use(cookieParser());
//app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
//app.use('/users', users);

//User 操作
app.post('/user', User.newUser);
app.get('/user', User.listUser);

//Idea 操作
app.post('/idea',Idea.newIdea);
app.get('/getIp',Idea.getIp);
app.get('/idea',Idea.listIdea);

//Ideaboard 操作
app.post('/ideaboard',Ideaboard.newIdeaboard);
app.get('/ideaboard',Ideaboard.listIdeaboard);
app.get('/api/:ideaboard',Idea.listHackathonIdea);

app.get('/users', function(req, res, next) {
    //return next(error(401, 'user list is empty'));
    return res.send("test_user");
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

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

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

if (!module.parent) {
  app.listen(3009);
  console.log("Express started at 3009");
}

module.exports = app;
<|endoftext|>


<commit_before>Contacts = new Mongo.Collection("contacts");

var contact = {
  name: "",
  title: "",
  organization: "",
  phone: "",
  email: "",
  address: "",
  //tags: "",
  notes: ""
}

var parseForm = function (e) {
  var formData = new Object();
  formData = contact;
  for (var prop in formData) {
    if (formData.hasOwnProperty(prop)) {
      formData[prop] = e.target[prop].value;
    }
  }
  return formData;
}

Router.configure({
  layoutTemplate: "Layout"  // the default layout
});

Router.route('/', function () {
  this.layout("Layout");
  this.render("Home");
});

Router.route('/email', function () {
  this.layout("Layout");
  this.render("EmailStakeholders");
});

Router.route('/categories', function () {
  this.layout("Layout");
  this.render("Categories");
});

TabularTables = {};

TabularTables.Contacts = new Tabular.Table({
  collection: Contacts,
  columns: [
    {data: "name", title: "NAME"},
    {data: "title", title: "TITLE"},
    {data: "organization", title: "ORGANIZATION"},
    {data: "phone", title: "PHONE"},
    {data: "email", title: "EMAIL"},
    {data: "address", title: "ADDDRESS"},
    {data: "tags", title: "TAGS"},
    {data: "notes", title: "NOTES"}
  ],
  name: "ContactsList",
  responsive: true
});

if (Meteor.isClient) {

  Template.registerHelper("TabularTables", TabularTables);

  Template.ContactsList.helpers({
    contacts: function () {
      return Contacts.find({}, { sort: { name: 1 }});
    }
  });

  Template.body.events({
    "submit .new-contact": function (event) {
      var form = parseForm(event);
      form["lastModifiedDate"] = new Date();
      Contacts.insert(form);
      $('#addContactModal').modal('hide');
      Router.go("/");
      return false; // Prevent default form submit
    }
  });

}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}
<commit_msg>Tags are inserted as an array of tags into the db<commit_after>Contacts = new Mongo.Collection("contacts");

var contact = {
  name: "",
  title: "",
  organization: "",
  phone: "",
  email: "",
  address: "",
  notes: ""
}

var parseForm = function (e) {
  var formData = new Object();
  formData = contact;
  for (var prop in formData) {
    if (formData.hasOwnProperty(prop)) {
      formData[prop] = e.target[prop].value;
    }
  }
  return formData;
}

Router.configure({
  layoutTemplate: "Layout"  // the default layout
});

Router.route('/', function () {
  this.layout("Layout");
  this.render("Home");
});

Router.route('/email', function () {
  this.layout("Layout");
  this.render("EmailStakeholders");
});

Router.route('/categories', function () {
  this.layout("Layout");
  this.render("Categories");
});

TabularTables = {};

TabularTables.Contacts = new Tabular.Table({
  collection: Contacts,
  columns: [
    {data: "name", title: "NAME"},
    {data: "title", title: "TITLE"},
    {data: "organization", title: "ORGANIZATION"},
    {data: "phone", title: "PHONE"},
    {data: "email", title: "EMAIL"},
    {data: "address", title: "ADDDRESS"},
    {data: "tags", title: "TAGS"},
    {data: "notes", title: "NOTES"}
  ],
  name: "ContactsList",
  responsive: true
});

if (Meteor.isClient) {

  Template.registerHelper("TabularTables", TabularTables);

  Template.ContactsList.helpers({
    contacts: function () {
      return Contacts.find({}, { sort: { name: 1 }});
    }
  });

  Template.body.events({
    "submit .new-contact": function (event) {
      var form = parseForm(event);
      form["lastModifiedDate"] = new Date();
      form["tags"] = $("#add-contact-tags").tagsinput('items'); // get tags from tag input
      console.log(form);
      Contacts.insert(form);
      $('#addContactModal').modal('hide');
      Router.go("/");
      return false; // Prevent default form submit
    }
  });

}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}
<|endoftext|>


<commit_before>var AWS = require('aws-sdk');
var express = require('express');
var bodyParser = require('body-parser');
var schedule = require('node-schedule');

AWS.config.region = process.env.REGION;

var AWSAccessKeyId = process.env.AWS_ACCESS_KEY_ID;
var AWSSecretKey = process.env.AWS_SECRET_KEY;
var sns = new AWS.SNS({region:"us-east-1",
        'accessKeyId': AWSAccessKeyId,
        'secretAccessKey': AWSSecretKey});
var snsInvTopic =  process.env.TRACK_INV_TOPIC || 'arn:aws:sns:us-east-1:419997458948:mmx-track-inv';
var snsImpTopic =  'arn:aws:sns:us-east-1:419997458948:mmx-track-imp';
var snsClickTopic =  'arn:aws:sns:us-east-1:419997458948:mmx-track-click';
var snsQuartileTopic =  'arn:aws:sns:us-east-1:419997458948:mmx-track-quartile';

var invScheduleTime = '*/5 * * * * *';
var impScheduleTime = '*/10 * * * * *';
var clickScheduleTime = '*/1 * * * *';
var quartileScheduleTime = '*/3 * * * * *';

var app = express();

app.set('view engine', 'ejs');
app.use('/static', express.static(__dirname + '/static'));
//app.use(express.static('static'));
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({extended:false}));

app.get('/', function(req, res) {
    res.render('index', {
        static_path: 'static',
        theme: process.env.THEME || 'flatly',
        flask_debug: process.env.FLASK_DEBUG || 'false'
    });
});

var port = process.env.PORT || 8080;
var counter = 0;

var invSchedule = schedule.scheduleJob(invScheduleTime, function(){
    console.log('Track Inventory Every 5 seconds: ', counter++);
    sns.publish({
        'Message': 'Track Inventory',
        'Subject': 'Track Inventory',
        'TopicArn': snsInvTopic
    }, function(err, data) {
        if (err) {
            console.log('SNS Error: ' + err);
        } else {
            console.log('SNS Success: ');
            console.log(data);
        }
    });
});

var impSchedule = schedule.scheduleJob(impScheduleTime, function(){
    console.log('Track Impression Every 60 seconds: ', counter++);
    sns.publish({
        'Message': 'Track Impression',
        'Subject': 'Track Impression',
        'TopicArn': snsImpTopic
    }, function(err, data) {
        if (err) {
            console.log('SNS Error: ' + err);
        } else {
            console.log('SNS Success: ');
            console.log(data);
        }
    });
});

var clickSchedule = schedule.scheduleJob(clickScheduleTime, function(){
    console.log('Track Click Every 300 seconds: ', counter++);
    sns.publish({
        'Message': 'Track Click',
        'Subject': 'Track Click',
        'TopicArn': snsClickTopic
    }, function(err, data) {
        if (err) {
            console.log('SNS Error: ' + err);
        } else {
            console.log('SNS Success: ');
            console.log(data);
        }
    });
});

var quartileSchedule = schedule.scheduleJob(quartileScheduleTime, function(){
    console.log('Track Quartile Every 60 seconds: ', counter++);
    sns.publish({
        'Message': 'Track Quartile',
        'Subject': 'Track Quartile',
        'TopicArn': snsQuartileTopic
    }, function(err, data) {
        if (err) {
            console.log('SNS Error: ' + err);
        } else {
            console.log('SNS Success: ');
            console.log(data);
        }
    });
});

var server = app.listen(port, function () {
    console.log('Server running on port' + port + '/');
});
<commit_msg>update timing<commit_after>var AWS = require('aws-sdk');
var express = require('express');
var bodyParser = require('body-parser');
var schedule = require('node-schedule');

AWS.config.region = process.env.REGION;

var AWSAccessKeyId = process.env.AWS_ACCESS_KEY_ID;
var AWSSecretKey = process.env.AWS_SECRET_KEY;
var sns = new AWS.SNS({region:"us-east-1",
        'accessKeyId': AWSAccessKeyId,
        'secretAccessKey': AWSSecretKey});
var snsInvTopic =  process.env.TRACK_INV_TOPIC || 'arn:aws:sns:us-east-1:419997458948:mmx-track-inv';
var snsImpTopic =  'arn:aws:sns:us-east-1:419997458948:mmx-track-imp';
var snsClickTopic =  'arn:aws:sns:us-east-1:419997458948:mmx-track-click';
var snsQuartileTopic =  'arn:aws:sns:us-east-1:419997458948:mmx-track-quartile';

var invScheduleTime = '*/1 * * * * *';
var impScheduleTime = '*/10 * * * * *';
var clickScheduleTime = '*/1 * * * *';
var quartileScheduleTime = '*/3 * * * * *';

var app = express();

app.set('view engine', 'ejs');
app.use('/static', express.static(__dirname + '/static'));
//app.use(express.static('static'));
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({extended:false}));

app.get('/', function(req, res) {
    res.render('index', {
        static_path: 'static',
        theme: process.env.THEME || 'flatly',
        flask_debug: process.env.FLASK_DEBUG || 'false'
    });
});

var port = process.env.PORT || 8080;
var counter = 0;

var invSchedule = schedule.scheduleJob(invScheduleTime, function(){
    console.log('Track Inventory Every 5 seconds: ', counter++);
    sns.publish({
        'Message': 'Track Inventory',
        'Subject': 'Track Inventory',
        'TopicArn': snsInvTopic
    }, function(err, data) {
        if (err) {
            console.log('SNS Error: ' + err);
        } else {
            console.log('SNS Success: ');
            console.log(data);
        }
    });
});

var impSchedule = schedule.scheduleJob(impScheduleTime, function(){
    console.log('Track Impression Every 60 seconds: ', counter++);
    sns.publish({
        'Message': 'Track Impression',
        'Subject': 'Track Impression',
        'TopicArn': snsImpTopic
    }, function(err, data) {
        if (err) {
            console.log('SNS Error: ' + err);
        } else {
            console.log('SNS Success: ');
            console.log(data);
        }
    });
});

var clickSchedule = schedule.scheduleJob(clickScheduleTime, function(){
    console.log('Track Click Every 300 seconds: ', counter++);
    sns.publish({
        'Message': 'Track Click',
        'Subject': 'Track Click',
        'TopicArn': snsClickTopic
    }, function(err, data) {
        if (err) {
            console.log('SNS Error: ' + err);
        } else {
            console.log('SNS Success: ');
            console.log(data);
        }
    });
});

var quartileSchedule = schedule.scheduleJob(quartileScheduleTime, function(){
    console.log('Track Quartile Every 60 seconds: ', counter++);
    sns.publish({
        'Message': 'Track Quartile',
        'Subject': 'Track Quartile',
        'TopicArn': snsQuartileTopic
    }, function(err, data) {
        if (err) {
            console.log('SNS Error: ' + err);
        } else {
            console.log('SNS Success: ');
            console.log(data);
        }
    });
});

var server = app.listen(port, function () {
    console.log('Server running on port' + port + '/');
});
<|endoftext|>


<commit_before>var path    = require('path'),
    express = require('express'),
    app     = express.createServer(),
    io      = require('socket.io').listen(app);

var config      = require('./config.js'),
    currentShow = require('./lib/show.js'),
    skripts     = require('./lib/skript.js').loadAllSkripts(config.skriptsPath);

var args = process.argv.slice(2);

var theaters = {
    irc: require('./lib/irctheater.js')
};

app.configure(function(){
    app.use(express.methodOverride());
    app.use(express.bodyParser());
    app.use(app.router);
});

app.configure('development', function() {
    app.use(express.static(__dirname + '/static'));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function() {
  var oneYear = 31557600000;
  app.use(express.static(__dirname + '/static', { maxAge: oneYear }));
  app.use(express.errorHandler());
});

app.get('/api/theatres', function(req, res) {
  res.send(JSON.stringify(theaters));
});

app.get('/api/skripts', function(req, res) {
  res.send(JSON.stringify(skripts));
});

app.post('/api/start/:id', function(req, res) {
  //currentShow.startShow(theaters.irc.getTheater(), skripts[req.params.id], function() {
    //io.sockets.emit('current show', currentShow.toJSON());
  //});
  res.send("");
});

app.get('/', function(req, res) {
  res.sendfile(path.join(__dirname, 'static', 'index.html'));
});

app.listen(config.port, config.host);

io.sockets.on('connection', function(socket) {
    socket.emit('current show', currentShow.toJSON());
});

if (args.length > 0){
    console.log("Running with", args[0]);
    var theater = theaters.irc.getTheater();
    var hamlet = skripts[args[0]];
    theater.setup(hamlet.setup, function(){
        theater.run(hamlet.skript);
    });
}
<commit_msg>Revert "Disable show"<commit_after>var path    = require('path'),
    express = require('express'),
    app     = express.createServer(),
    io      = require('socket.io').listen(app);

var config      = require('./config.js'),
    currentShow = require('./lib/show.js'),
    skripts     = require('./lib/skript.js').loadAllSkripts(config.skriptsPath);

var args = process.argv.slice(2);

var theaters = {
    irc: require('./lib/irctheater.js')
};

app.configure(function(){
    app.use(express.methodOverride());
    app.use(express.bodyParser());
    app.use(app.router);
});

app.configure('development', function() {
    app.use(express.static(__dirname + '/static'));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function() {
  var oneYear = 31557600000;
  app.use(express.static(__dirname + '/static', { maxAge: oneYear }));
  app.use(express.errorHandler());
});

app.get('/api/theatres', function(req, res) {
  res.send(JSON.stringify(theaters));
});

app.get('/api/skripts', function(req, res) {
  res.send(JSON.stringify(skripts));
});

app.post('/api/start/:id', function(req, res) {
  currentShow.startShow(theaters.irc.getTheater(), skripts[req.params.id], function() {
    io.sockets.emit('current show', currentShow.toJSON());
  });
  res.send("");
});

app.get('/', function(req, res) {
  res.sendfile(path.join(__dirname, 'static', 'index.html'));
});

app.listen(config.port, config.host);

io.sockets.on('connection', function(socket) {
    socket.emit('current show', currentShow.toJSON());
});

if (args.length > 0){
    console.log("Running with", args[0]);
    var theater = theaters.irc.getTheater();
    var hamlet = skripts[args[0]];
    theater.setup(hamlet.setup, function(){
        theater.run(hamlet.skript);
    });
}
<|endoftext|>