<commit_before>"use strict";

const express = require('express');
const bodyParser = require('body-parser');
const twilio = require('twilio');
const app = express();
const request = require('request');

var port = process.env.PORT || 8080; // set our port

// Run server to listen on port assigned by Heroku.
const server = app.listen(port, () => {
  console.log('listening on *:' + port);
});

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

// Set Express routes.
app.post('/events', (req, res) => {
  let to = req.body.To;
  let fromNumber = req.body.From;
  let callStatus = req.body.CallStatus;
  let callSid = req.body.CallSid;

	var options = { method: 'POST',
		  url: process.env.URL +'/rest/servicedeskapi/request',
		  headers:
		   { 'authorization: 'Basic'+ port.env.TOKEN },
		  body:
		   { serviceDeskId: '1',
			 requestTypeId: '1',
			 requestFieldValues:
			  { summary: 'Inbound Phone request from ' + fromNumber,
				description: 'A request has been received via phone' } },
		  json: true };

		request(options, function (error, response, body) {
		  if (error) throw new Error(error);
		console.log(body);

		});

console.log(to, fromNumber, callStatus, callSid);
  res.send('Event received');
});
<commit_msg>Added voice route<commit_after>"use strict";

const express = require('express');
const bodyParser = require('body-parser');
const twilio = require('twilio');
const app = express();
const request = require('request');

var port = process.env.PORT || 8080; // set our port

// Run server to listen on port assigned by Heroku.
const server = app.listen(port, () => {
  console.log('listening on *:' + port);
});

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

// Set Express routes.
app.post('/events', (req, res) => {
  let to = req.body.To;
  let fromNumber = req.body.From;
  let callStatus = req.body.CallStatus;
  let callSid = req.body.CallSid;

	var options = { method: 'POST',
		  url: process.env.URL +'/rest/servicedeskapi/request',
		  headers:
		   { 'authorization: 'Basic'+ port.env.TOKEN },
		  body:
		   { serviceDeskId: '1',
			 requestTypeId: '1',
			 requestFieldValues:
			  { summary: 'Inbound Phone request from ' + fromNumber,
				description: 'A request has been received via phone' } },
		  json: true };

		request(options, function (error, response, body) {
		  if (error) throw new Error(error);
		console.log(body);

		});

console.log(to, fromNumber, callStatus, callSid);
  res.send('Event received');
});

app.post('/voice', (req, res) => {
  // Generate a TwiML response
  let twiml = new twilio.TwimlResponse();
  // Talk in a robot voice over the phone.
  twiml.say('Call progress events are rad');
  // Set the response type as XML.
  res.header('Content-Type', 'text/xml');
  // Send the TwiML as the response.
  res.send(twiml.toString());
});
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var express = require('express')
  , controller = require('./controllers')
  , adminController = require('./controllers/admin/index')
  , voteController = require('./controllers/vote/index')

    , Resource = require('express-resource-new')
  //, Resource = require('express-resource')
  , http = require('http')
  , passport = require('passport')
  , passportConfig = require('./config/passport.conf')
  , path = require('path')
  , MongoStore = require('connect-mongo')(express)
  , ConfigSettings = require('./config/settings')

// passport: Login initialization
passportConfig.initializePassport();

var app = express();
var settings = ConfigSettings.getSettings();

function errorHandler(err, req, res, next) {
    res.status(500);
    res.json(err);
    //res.render('error', { error: err });
}

function clientErrorHandler(err, req, res, next) {
    if (req.xhr) {
        res.send(500, { error: 'Something blew up!' });
    } else {
        next(err);
    }
}

// configuration
app.configure(function(){
    app.set('port', process.env.PORT || 3000);
    app.set('views', path.join(__dirname, 'clientApp/views'));
    app.set('view engine', 'jade');
    app.set('controllers', path.join(__dirname, 'controllers'));

    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());

    app.use(express.cookieParser());
    //app.use(express.session({ secret: 'dorIsGarbash' }));

    app.use(express.session({
        secret: settings.cookie_secret,
        store: new MongoStore({
            url: settings.session_db_url,
            db: settings.session_db
        })
    }));

    app.use(passport.initialize());
    app.use(passport.session());

    app.use('/js', express.static(path.join(__dirname, 'clientApp/js')));
    app.use('/css', express.static(path.join(__dirname, 'clientApp/css')));
    app.use('/img', express.static(path.join(__dirname, 'clientApp/img')));
    app.use(app.router);
});

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

app.configure('production', function(){
    app.use(clientErrorHandler);
});
*/

// routing
app.resource('resources', function() {
    this.member.get('searchByKeyword');
    this.member.get('triplets');
    this.collection.post('findByUrl');
});

app.resource('wiki');

app.resource('connections', function() {
    this.collection.post('latestTriplets');
    this.collection.post('hottestTriplets');
    this.member.get('getTripletByConnectionId');
    this.member.get('getTripletsByUserId');
});

app.post('/vote/voteUp',voteController.voteUp );
app.post('/vote/voteDown',voteController.voteDown );
app.post('/vote/cancelVote',voteController.cancelVote );

app.resource('scrape');

app.post('/admin/indexAllResources', adminController.indexAllResources);
app.post('/admin/indexAllConnections', adminController.indexAllConnections);

app.resource('edges');
app.resource('comments', function () {
    this.member.get('getRelatedComments');
});
app.resource('concepts', function () {
    //this.collection.get('getRelatedKnownodes');
    this.member.get('getRelatedKnownodes');
    this.member.get('getRelatedComments');
    this.resource('knownodes', function() {
    });
});
app.resource('knownodes', function () {
    this.member.get('getRelatedKnownodes');
    this.member.get('getRelatedComments');
    this.member.get('getNodesByKeyword');

    this.collection.post('getResourceByUrl');
    this.collection.post('wikinodeIfExists');
    this.collection.post('wikinode');
    this.collection.post('scrapeUrl');

    this.resource('knownodes', { id: 'related' });
    this.resource('files');
    this.resource('comments');
});
app.resource('files', { name: 'knownodeFiles', id: 'files'});
//app.get('/concepts/:cid/knownodes/:kid', require('./routes/API.concept').load, require('./routes/API.knownode').load);

app.post('/logout', function(req, res){
    req.logout();
    res.json({ success: "Logout" });
});

app.post('/login', function (req, res, next) {
    passport.authenticate('local', function (err, user, info) {
        if (err) { return next(err); }
        if (!user) {
            //req.flash('error', info.message);
            //return res.redirect('/login')
            return res.send('ERROR');
        }
        req.logIn(user, function (err) {
            return err ? next(err) : res.send(user);
        });
    })(req, res, next);
});

app.get('/auth/facebook',
    passport.authenticate('facebook', {  scope: [ 'email' ] }),
    function (req, res) {
        // The request will be redirected to Facebook for authentication, so this
        // function will not be called.
    });

app.get('/auth/facebook/callback',
    passport.authenticate('facebook', { failureRedirect: '/login' }),
    function (req, res) {
        res.redirect('/');
    });

app.get('/auth/google',
    passport.authenticate('google', { failureRedirect: '/login' }),
    function (req, res) {
        // The request will be redirected to Google for authentication, so
        // this function will not be called.
    });

app.get('/auth/google/callback',
    passport.authenticate('google', { failureRedirect: '/login' }),
    function (req, res) {
        // Successful authentication, redirect home.
        res.redirect('/');
    });

// routing fallback - MUST (!!) be the last line of all routing
app.get('/', controller.index);
app.get('/partials/:dir/:name', controller.partialsDir);
app.get('/partials/:name', controller.partials);
app.get('/screens/:name', controller.screens);

app.get('*', controller.index);

/*
app.get('/', function(request, response) {
    response.redirect('/knownodes');
});
*/

// let's do it!
http.createServer(app).listen(app.get('port'), function () {
    console.log("Express server listening on port " + app.get('port'));
});
<commit_msg>minor bug fix<commit_after>/**
 * Module dependencies.
 */
var express = require('express')
  , controller = require('./controllers')
  , adminController = require('./controllers/admin/index')
  , voteController = require('./controllers/vote/index')

    , Resource = require('express-resource-new')
  //, Resource = require('express-resource')
  , http = require('http')
  , passport = require('passport')
  , passportConfig = require('./config/passport.conf')
  , path = require('path')
  , MongoStore = require('connect-mongo')(express)
  , ConfigSettings = require('./config/settings')

// passport: Login initialization
passportConfig.initializePassport();

var app = express();
var settings = ConfigSettings.getSettings();

function errorHandler(err, req, res, next) {
    res.status(500);
    res.json(err);
    //res.render('error', { error: err });
}

function clientErrorHandler(err, req, res, next) {
    if (req.xhr) {
        res.send(500, { error: 'Something blew up!' });
    } else {
        next(err);
    }
}

// configuration
app.configure(function(){
    app.set('port', process.env.PORT || 3000);
    app.set('views', path.join(__dirname, 'clientApp/views'));
    app.set('view engine', 'jade');
    app.set('controllers', path.join(__dirname, 'controllers'));

    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());

    app.use(express.cookieParser());
    //app.use(express.session({ secret: 'dorIsGarbash' }));

    app.use(express.session({
        secret: settings.cookie_secret,
        store: new MongoStore({
            url: settings.session_db_url,
            db: settings.session_db
        })
    }));

    app.use(passport.initialize());
    app.use(passport.session());

    app.use('/js', express.static(path.join(__dirname, 'clientApp/js')));
    app.use('/css', express.static(path.join(__dirname, 'clientApp/css')));
    app.use('/img', express.static(path.join(__dirname, 'clientApp/img')));
    app.use(app.router);
});

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

app.configure('production', function(){
    app.use(clientErrorHandler);
});
*/

// routing
app.resource('resources', function() {
    this.member.get('searchByKeyword');
    this.member.get('triplets');
    this.collection.post('findByUrl');
});

app.resource('wiki');

app.resource('connections', function() {
    this.collection.post('latestTriplets');
    this.collection.post('hottestTriplets');
    this.member.get('getTripletByConnectionId');
    this.member.get('getTripletsByUserId');
});

app.post('/vote/voteUp',voteController.voteUp );
app.post('/vote/voteDown',voteController.voteDown );
app.post('/vote/cancelVote',voteController.cancelVote );

app.resource('scrape');
app.resource('users');

app.post('/admin/indexAllResources', adminController.indexAllResources);
app.post('/admin/indexAllConnections', adminController.indexAllConnections);

app.resource('edges');
app.resource('comments', function () {
    this.member.get('getRelatedComments');
});
app.resource('concepts', function () {
    //this.collection.get('getRelatedKnownodes');
    this.member.get('getRelatedKnownodes');
    this.member.get('getRelatedComments');
    this.resource('knownodes', function() {
    });
});
app.resource('knownodes', function () {
    this.member.get('getRelatedKnownodes');
    this.member.get('getRelatedComments');
    this.member.get('getNodesByKeyword');

    this.collection.post('getResourceByUrl');
    this.collection.post('wikinodeIfExists');
    this.collection.post('wikinode');
    this.collection.post('scrapeUrl');

    this.resource('knownodes', { id: 'related' });
    this.resource('files');
    this.resource('comments');
});
app.resource('files', { name: 'knownodeFiles', id: 'files'});
//app.get('/concepts/:cid/knownodes/:kid', require('./routes/API.concept').load, require('./routes/API.knownode').load);

app.post('/logout', function(req, res){
    req.logout();
    res.json({ success: "Logout" });
});

app.post('/login', function (req, res, next) {
    passport.authenticate('local', function (err, user, info) {
        if (err) { return next(err); }
        if (!user) {
            //req.flash('error', info.message);
            //return res.redirect('/login')
            return res.send('ERROR');
        }
        req.logIn(user, function (err) {
            return err ? next(err) : res.send(user);
        });
    })(req, res, next);
});

app.get('/auth/facebook',
    passport.authenticate('facebook', {  scope: [ 'email' ] }),
    function (req, res) {
        // The request will be redirected to Facebook for authentication, so this
        // function will not be called.
    });

app.get('/auth/facebook/callback',
    passport.authenticate('facebook', { failureRedirect: '/login' }),
    function (req, res) {
        res.redirect('/');
    });

app.get('/auth/google',
    passport.authenticate('google', { failureRedirect: '/login' }),
    function (req, res) {
        // The request will be redirected to Google for authentication, so
        // this function will not be called.
    });

app.get('/auth/google/callback',
    passport.authenticate('google', { failureRedirect: '/login' }),
    function (req, res) {
        // Successful authentication, redirect home.
        res.redirect('/');
    });

// routing fallback - MUST (!!) be the last line of all routing
app.get('/', controller.index);
app.get('/partials/:dir/:name', controller.partialsDir);
app.get('/partials/:name', controller.partials);
app.get('/screens/:name', controller.screens);

app.get('*', controller.index);

/*
app.get('/', function(request, response) {
    response.redirect('/knownodes');
});
*/

// let's do it!
http.createServer(app).listen(app.get('port'), function () {
    console.log("Express server listening on port " + app.get('port'));
});
<|endoftext|>


<commit_before>'use strict';

function hitGiphyAPI(translationPhrase) {
  var gif = null;
  request({
    uri: "http://api.giphy.com/v1/gifs/translate",
    qs: { s: translationPhrase, api_key: GIPHY_API_TOKEN }
  }, function(error, response, body) {
    if (!error && response.statusCode == 200) {
      gif = JSON.parse(body).data.images.fixed_height.url;
      console.log("gif inside is: ");
      console.log(gif)
    } else {
      console.log("EEEERRRRRROOOOOORRRRRR");
      console.log(response.statusCode);
      console.log(error);
    }
  });
  console.log("gif outside is: ")
  console.log(gif);
  return gif
}

function shouldTakeAction(text) {
  return /^gifacle\s.*/.test(text);
}

function parseMessage(text) {
  return /^gifacle\s(.*)/.exec(text)[1]
}

function gifParty() {
}

function gifTranslate() {
}

function isTextMessage(msg) {
  return msg.message;
}

function callSendAPI(message) {
  request({
    uri: 'https://graph.facebook.com/v2.8/me/messages',
    qs: { access_token: PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: message

  } , function (error, response, body) {
    if (!error && response.statusCode== 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Succesfully sent message with id %s to recipient %s", messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

function sendGif(sendTo, gif) {
  var messageData = {
    recipient: {
      id: sendTo
    },
    message: {
      attachment: {
        type: "image",
        payload: {
          url: gif
        }
      }
    }
  };

  callSendAPI(messageData);
}

function handleTextMessage(msg) {
  var senderID = msg.sender.id;
  var recipientID = msg.recipient.id;
  var timeOfMessage= msg.timestamp;
  var message = msg.message;

  console.log("Received message for user %d and page %d at %d with message: ", senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  var messageText = message.text;

  if (messageText) {
    if (shouldTakeAction(messageText)) {
      var phrase = parseMessage(messageText);
      console.log(phrase);
      var gif = hitGiphyAPI(phrase);
      if (gif != null) {
        sendGif(senderID, gif);
      } else {
        sendTextMessage(senderID, "could not match phrase");
      }
    }
  }
}

function sendTextMessage(sendTo, msg) {
  var messageData = {
    recipient: {
      id: sendTo
    },
    message: {
      text: msg
    }
  };

  callSendAPI(messageData);
}

function verifyRequestSignature(req, res, buf) {
  var signature = req.headers["x-hub-signature"];

  if (!signature) {
    // For testing, let's log an error. In production, you should throw an
    // error.
    console.error("Couldn't validate the signature.");
  } else {
    var elements = signature.split('=');
    var method = elements[0];
    var signatureHash = elements[1];

    var expectedHash = crypto.createHmac('sha1', APP_SECRET)
        .update(buf)
        .digest('hex');

    if (signatureHash != expectedHash) {
      throw new Error("Couldn't validate the request signature.");
    }
  }
}

const bodyParser = require('body-parser')
const express = require('express');
const https = require('https');
const request = require('request');
const crypto = require('crypto');

var app = express();
app.set('port', process.env.PORT || 5000);
app.use(bodyParser.json({ verify: verifyRequestSignature }));
app.use(express.static('public'));

const VALIDATION_TOKEN = process.env.VALIDATION_TOKEN;
const PAGE_ACCESS_TOKEN = process.env.PAGE_ACCESS_TOKEN;
const APP_SECRET = process.env.APP_SECRET;
const GIPHY_API_TOKEN = "dc6zaTOxFJmzC";

if (!VALIDATION_TOKEN) {
  console.error("VALIDATION_TOKEN missing");
  process.exit(1);
}

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

// Routes
app.get('/webhook', function(req, res) {
  if (req.query['hub.verify_token'] === VALIDATION_TOKEN) {
    console.log("Validating webhook");
    res.status(200).send(req.query['hub.challenge']);
  } else {
    console.error("Failed validation. Make sure the validation tokens match.");
    res.sendStatus(403);
  }
});

app.post('/webhook', function (req, res) {
//  console.log(req)
  var data = req.body;
  console.log(data);

  if (data.object == 'page') {
    data.entry.forEach(function (pageEntry) {
      pageEntry.messaging.forEach(function (msg) {
        if (isTextMessage(msg)) {
          handleTextMessage(msg)
          // ignore others for now
          // TODO: do not ignore
        }
      });
    });
  }
  res.sendStatus(200);
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});
<commit_msg>think asynchronously<commit_after>'use strict';

function hitGiphyAPI(translationPhrase, fn) {
  var gif = null;
  request({
    uri: "http://api.giphy.com/v1/gifs/translate",
    qs: { s: translationPhrase, api_key: GIPHY_API_TOKEN }
  }, function(error, response, body) {
    if (!error && response.statusCode == 200) {
      gif = JSON.parse(body).data.images.fixed_height.url;
      fn(gif);
    } else {
      console.log("EEEERRRRRROOOOOORRRRRR");
      console.log(response.statusCode);
      console.log(error);
      fn(null);
    }
  });
}

function shouldTakeAction(text) {
  return /^gifacle\s.*/.test(text);
}

function parseMessage(text) {
  return /^gifacle\s(.*)/.exec(text)[1]
}

function gifParty() {
}

function gifTranslate() {
}

function isTextMessage(msg) {
  return msg.message;
}

function callSendAPI(message) {
  request({
    uri: 'https://graph.facebook.com/v2.8/me/messages',
    qs: { access_token: PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: message

  } , function (error, response, body) {
    if (!error && response.statusCode== 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Succesfully sent message with id %s to recipient %s", messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

function sendGif(sendTo, gif) {
  var messageData = {
    recipient: {
      id: sendTo
    },
    message: {
      attachment: {
        type: "image",
        payload: {
          url: gif
        }
      }
    }
  };

  callSendAPI(messageData);
}

function handleTextMessage(msg) {
  var senderID = msg.sender.id;
  var recipientID = msg.recipient.id;
  var timeOfMessage= msg.timestamp;
  var message = msg.message;

  console.log("Received message for user %d and page %d at %d with message: ", senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  var messageText = message.text;

  if (messageText) {
    if (shouldTakeAction(messageText)) {
      var phrase = parseMessage(messageText);
      console.log(phrase);
      hitGiphyAPI(phrase, function (gif) {
        if (gif != null) {
          sendGif(senderID, gif);
        } else {
          sendTextMessage(senderID, "could not match phrase");
        }
      });
    }
  }
}

function sendTextMessage(sendTo, msg) {
  var messageData = {
    recipient: {
      id: sendTo
    },
    message: {
      text: msg
    }
  };

  callSendAPI(messageData);
}

function verifyRequestSignature(req, res, buf) {
  var signature = req.headers["x-hub-signature"];

  if (!signature) {
    // For testing, let's log an error. In production, you should throw an
    // error.
    console.error("Couldn't validate the signature.");
  } else {
    var elements = signature.split('=');
    var method = elements[0];
    var signatureHash = elements[1];

    var expectedHash = crypto.createHmac('sha1', APP_SECRET)
        .update(buf)
        .digest('hex');

    if (signatureHash != expectedHash) {
      throw new Error("Couldn't validate the request signature.");
    }
  }
}

const bodyParser = require('body-parser')
const express = require('express');
const https = require('https');
const request = require('request');
const crypto = require('crypto');

var app = express();
app.set('port', process.env.PORT || 5000);
app.use(bodyParser.json({ verify: verifyRequestSignature }));
app.use(express.static('public'));

const VALIDATION_TOKEN = process.env.VALIDATION_TOKEN;
const PAGE_ACCESS_TOKEN = process.env.PAGE_ACCESS_TOKEN;
const APP_SECRET = process.env.APP_SECRET;
const GIPHY_API_TOKEN = "dc6zaTOxFJmzC";

if (!VALIDATION_TOKEN) {
  console.error("VALIDATION_TOKEN missing");
  process.exit(1);
}

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

// Routes
app.get('/webhook', function(req, res) {
  if (req.query['hub.verify_token'] === VALIDATION_TOKEN) {
    console.log("Validating webhook");
    res.status(200).send(req.query['hub.challenge']);
  } else {
    console.error("Failed validation. Make sure the validation tokens match.");
    res.sendStatus(403);
  }
});

app.post('/webhook', function (req, res) {
//  console.log(req)
  var data = req.body;
  console.log(data);

  if (data.object == 'page') {
    data.entry.forEach(function (pageEntry) {
      pageEntry.messaging.forEach(function (msg) {
        if (isTextMessage(msg)) {
          handleTextMessage(msg)
          // ignore others for now
          // TODO: do not ignore
        }
      });
    });
  }
  res.sendStatus(200);
});

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


<commit_before>var express = require('express'),
	i18n = require('i18n'),
	request = require('request'),
	commit = null,
	moment = require('moment'),
	fs = require('fs'),
	async = require('async');

var app = express();

i18n.configure({
	locales:['en'],
	defaultLocale: 'en',
	directory: __dirname + '/locales',
	updateFiles: false
});

app.use(i18n.init);

app.use(express.static(__dirname + '/assets'));
app.set('view engine', 'ejs');

updateCache = function(cb){
	async.parallel({
		details: function(callback){
			request('https://api.github.com/repos/SilenceIM/Silence', {timeout: parseInt(process.env.TIMEOUT) || 2000, headers: {'User-Agent': 'SMSSecure Website'}}, function (err, res) {
				if (err || typeof res == 'undefined' || typeof res.statusCode == 'undefined' || res.statusCode != 200) return callback(true);
				fs.writeFile('./cache-details.json', res.body, function (err) {
					if (err) return callback("Cannot write cache-details.json");
					return callback(null, JSON.parse(res.body));
				});
			});
		},
		commits: function(callback){
			request('https://api.github.com/repos/SilenceIM/Silence/commits', {timeout: parseInt(process.env.TIMEOUT) || 2000, headers: {'User-Agent': 'SMSSecure Website'}}, function (err, res) {
				if (err || typeof res == 'undefined' || typeof res.statusCode == 'undefined' || res.statusCode != 200) return callback(true);
				fs.writeFile('./cache-commits.json', res.body, function (err) {
					if (err) return callback("Cannot write cache-commits.json");
					return callback(null, JSON.parse(res.body));
				});
			});
		}
	}, function(err, json){
		return cb(err, json);
	});
};

getCache = function(cb){
	async.parallel({
		commits: function(callback){
			fs.readFile('./cache-commits.json', function (err, data) {
				if (err) return callback(err);
				return callback(null, JSON.parse(data));
			});
		},
		details: function(callback){
			fs.readFile('./cache-details.json', function (err, data) {
				if (err) return callback(err);
				return callback(null, JSON.parse(data));
			});
		}
	}, function(err, json){
		return cb(err, json);
	})
};

getCacheTime = function(callback){
	fs.stat('./cache-commits.json', function(err, stats){
		if (err) return callback(err);
		return callback(null, Math.floor((new Date().getTime()-stats.mtime.getTime())/1000/60));
	});
};

getData = function(callback){
	getCacheTime(function(err, time){
		var cache = parseInt(process.env.CACHE) || 5;
		if (err || time >= cache){
			updateCache(function(err, json){
				console.log('Updating cache...');
				return callback(err, json);
			});
		} else {
			getCache(function(err, json){
				console.log('Using cache...');
				return callback(err, json);
			});
		}
	});
};

app.get('/', function (req, res) {

	moment.locale(res.locale);

	getData(function(err, json){
		if (err) console.log(err);
		if (!err){
			commit = {};
			commit.message = json.commits[0].commit.message.split('\n')[0];
			commit.date = moment(json.commits[0].commit.author.date).fromNow();
			commit.author = json.commits[0].author.login;
			commit.link = 'https://github.com/SilenceIM/Silence/commit/'+json.commits[0].sha;
		}
		return res.render('index', {req: req, res: res, commit: commit, github: json.details});
	});
})

var server = app.listen(parseInt(process.env.PORT) || 3000, function () {
	console.log('App listening at http://%s:%s', server.address().address, server.address().port);
})
<commit_msg>fix name<commit_after>var express = require('express'),
	i18n = require('i18n'),
	request = require('request'),
	commit = null,
	moment = require('moment'),
	fs = require('fs'),
	async = require('async');

var app = express();

i18n.configure({
	locales:['en'],
	defaultLocale: 'en',
	directory: __dirname + '/locales',
	updateFiles: false
});

app.use(i18n.init);

app.use(express.static(__dirname + '/assets'));
app.set('view engine', 'ejs');

updateCache = function(cb){
	async.parallel({
		details: function(callback){
			request('https://api.github.com/repos/SilenceIM/Silence', {timeout: parseInt(process.env.TIMEOUT) || 2000, headers: {'User-Agent': 'Silence Website'}}, function (err, res) {
				if (err || typeof res == 'undefined' || typeof res.statusCode == 'undefined' || res.statusCode != 200) return callback(true);
				fs.writeFile('./cache-details.json', res.body, function (err) {
					if (err) return callback("Cannot write cache-details.json");
					return callback(null, JSON.parse(res.body));
				});
			});
		},
		commits: function(callback){
			request('https://api.github.com/repos/SilenceIM/Silence/commits', {timeout: parseInt(process.env.TIMEOUT) || 2000, headers: {'User-Agent': 'Silence Website'}}, function (err, res) {
				if (err || typeof res == 'undefined' || typeof res.statusCode == 'undefined' || res.statusCode != 200) return callback(true);
				fs.writeFile('./cache-commits.json', res.body, function (err) {
					if (err) return callback("Cannot write cache-commits.json");
					return callback(null, JSON.parse(res.body));
				});
			});
		}
	}, function(err, json){
		return cb(err, json);
	});
};

getCache = function(cb){
	async.parallel({
		commits: function(callback){
			fs.readFile('./cache-commits.json', function (err, data) {
				if (err) return callback(err);
				return callback(null, JSON.parse(data));
			});
		},
		details: function(callback){
			fs.readFile('./cache-details.json', function (err, data) {
				if (err) return callback(err);
				return callback(null, JSON.parse(data));
			});
		}
	}, function(err, json){
		return cb(err, json);
	})
};

getCacheTime = function(callback){
	fs.stat('./cache-commits.json', function(err, stats){
		if (err) return callback(err);
		return callback(null, Math.floor((new Date().getTime()-stats.mtime.getTime())/1000/60));
	});
};

getData = function(callback){
	getCacheTime(function(err, time){
		var cache = parseInt(process.env.CACHE) || 5;
		if (err || time >= cache){
			updateCache(function(err, json){
				console.log('Updating cache...');
				return callback(err, json);
			});
		} else {
			getCache(function(err, json){
				console.log('Using cache...');
				return callback(err, json);
			});
		}
	});
};

app.get('/', function (req, res) {

	moment.locale(res.locale);

	getData(function(err, json){
		if (err) console.log(err);
		if (!err){
			commit = {};
			commit.message = json.commits[0].commit.message.split('\n')[0];
			commit.date = moment(json.commits[0].commit.author.date).fromNow();
			commit.author = json.commits[0].author.login;
			commit.link = 'https://github.com/SilenceIM/Silence/commit/'+json.commits[0].sha;
		}
		return res.render('index', {req: req, res: res, commit: commit, github: json.details});
	});
})

var server = app.listen(parseInt(process.env.PORT) || 3000, function () {
	console.log('App listening at http://%s:%s', server.address().address, server.address().port);
})
<|endoftext|>


<commit_before>  // **My2Cents** is a campaign widget for calling elected
  // representatives. Source is available on
  // [GitHub](https://github.com/affinitybridge/my2cents).

  // My2Cents is built on [Express](http://expressjs.com/). It uses the
  // [Twilio API](http://twilio.com) to make phone calls and the
  // [Open North Represent API](http://represent.opennorth.ca/) to receive
  // representative information. [Jade](http://jade-lang.com/) is used for templating and
  // [Stylus](http://learnboost.github.com/stylus/) helps with CSS.
(function() {
  var express = require('express'),
      passport = require('passport'),
      stylus = require('stylus'),
      config = require('./config');

  // Create the Express server.
  var app = module.exports = express.createServer();

  // Stylus compile function. [[docs](http://learnboost.github.com/stylus/docs/middleware.html)]
  function compile(str, path) {
    return stylus(str)
      .set('filename', path)
      // Comment the processed CSS when not on production
      .set('linenos', process.env.NODE_ENV !== 'production')
      // Compress the processed CSS
      .set('compress', true);
  }

  // Configure Express application.
  // Express uses [Connect](http://www.senchalabs.org/connect/) middleware.

  var oneMonth = 1000 * 60 * 60 * 24 * 30;

  app.configure(function() {
    app.use(stylus.middleware({
      src: __dirname + '/styles',
      dest: __dirname + '/public',
      compile: compile
    }));
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.set('port', process.env.PORT || 5000);
    app.use(express.logger());
    app.use(express.bodyParser());
    app.use(express.compress());
    app.use(express.static(__dirname + '/public', { maxAge: oneMonth }));
    app.use(express.cookieParser());
    app.use(express.session({secret: process.env.SESSION_SECRET || config.session_secret}));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(express.favicon('public/favicon.ico', { maxAge: oneMonth }));
  });

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

  app.configure('test', function(){
    app.set('port', 5001);
  });

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

  // Dynamic view helpers
  app.dynamicHelpers({
    flash: function (req, res) {
      return req.flash();
    }
  });

  // User authentication middleware
  function requireAuth(req, res, next) {
    if (req.session.user) {
      next();
    }
    else {
      req.flash('error', 'Please login to access this page!');
      res.redirect('/login');
    }
  }

  // ### Routes

  // Homepage
  require('./routes/index')(app);
  // User authentication
  require('./routes/login')(app);
  // User creation
  require('./routes/user')(app);
  // User dashboard
  require('./routes/dashboard')(app, requireAuth);
  // Display and create campaigns
  require('./routes/campaign')(app, requireAuth);
  // Get OpenNorth Represent data
  require('./routes/representatives')(app);
  // Twilio app request URL
  require('./routes/twiml')(app);

  // Bind the Express server to a port.
  var port = app.settings.port;
  app.listen(port, function() {
    console.log("Listening on " + port);
  });
}());
<commit_msg>Remove IIFE<commit_after>// **My2Cents** is a campaign widget for calling elected
// representatives. Source is available on
// [GitHub](https://github.com/affinitybridge/my2cents).

// My2Cents is built on [Express](http://expressjs.com/). It uses the
// [Twilio API](http://twilio.com) to make phone calls and the
// [Open North Represent API](http://represent.opennorth.ca/) to receive
// representative information. [Jade](http://jade-lang.com/) is used for templating and
// [Stylus](http://learnboost.github.com/stylus/) helps with CSS.

var express = require('express'),
    passport = require('passport'),
    stylus = require('stylus'),
    config = require('./config');

// Create the Express server.
var app = module.exports = express.createServer();

// Stylus compile function. [[docs](http://learnboost.github.com/stylus/docs/middleware.html)]
function compile(str, path) {
  return stylus(str)
    .set('filename', path)
    // Comment the processed CSS when not on production
    .set('linenos', process.env.NODE_ENV !== 'production')
    // Compress the processed CSS
    .set('compress', true);
}

// Configure Express application.
// Express uses [Connect](http://www.senchalabs.org/connect/) middleware.

var oneMonth = 1000 * 60 * 60 * 24 * 30;

app.configure(function() {
  app.use(stylus.middleware({
    src: __dirname + '/styles',
    dest: __dirname + '/public',
    compile: compile
  }));
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('port', process.env.PORT || 5000);
  app.use(express.logger());
  app.use(express.bodyParser());
  app.use(express.compress());
  app.use(express.static(__dirname + '/public', { maxAge: oneMonth }));
  app.use(express.cookieParser());
  app.use(express.session({secret: process.env.SESSION_SECRET || config.session_secret}));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(express.favicon('public/favicon.ico', { maxAge: oneMonth }));
});

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

app.configure('test', function(){
  app.set('port', 5001);
});

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

// Dynamic view helpers
app.dynamicHelpers({
  flash: function (req, res) {
    return req.flash();
  }
});

// User authentication middleware
function requireAuth(req, res, next) {
  if (req.session.user) {
    next();
  }
  else {
    req.flash('error', 'Please login to access this page!');
    res.redirect('/login');
  }
}

// ### Routes

// Homepage
require('./routes/index')(app);
// User authentication
require('./routes/login')(app);
// User creation
require('./routes/user')(app);
// User dashboard
require('./routes/dashboard')(app, requireAuth);
// Display and create campaigns
require('./routes/campaign')(app, requireAuth);
// Get OpenNorth Represent data
require('./routes/representatives')(app);
// Twilio app request URL
require('./routes/twiml')(app);

// Bind the Express server to a port.
var port = app.settings.port;
app.listen(port, function() {
  console.log("Listening on " + port);
});
<|endoftext|>


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

var routes  = require('./routes');
var http    = require('http');
var path    = require('path');

var app     = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

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

app.get('/', routes.index);
app.get('/rt', routes.index);
app.get('/rt/:stopid', routes.rt);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>Comment out favicon. No icon added to project<commit_after>var express = require('express');

var routes  = require('./routes');
var http    = require('http');
var path    = require('path');

var app     = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');

// app.use(express.favicon('public/images/fav.ico'));
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

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

app.get('/', routes.index);
app.get('/rt', routes.index);
app.get('/rt/:stopid', routes.rt);

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


<commit_before>// Here is the starting point for your application code.
// All stuff below is just to show you how it works. You can delete all of it.

// Use new ES6 modules syntax for everything.
/*import os from 'os'; // native node.js module
import { remote } from 'electron'; // native electron module
import jetpack from 'fs-jetpack'; // module loaded from npm
import { greet } from './hello_world/hello_world'; // code authored by you in this project
import env from './env';*/

const os = require('os');
const electron = require('electron');
const { remote } = electron;
const jetpack = require('fs-jetpack');
const request = require('request');
const showdown = require('showdown');
const Handlebars = require('handlebars');
const AdmZip = require('adm-zip');

var app = remote.app;
var appDir = jetpack.cwd(app.getAppPath());

const {webFrame} = electron;
webFrame.setZoomFactor(1.4);

// Holy crap! This is browser window with HTML and stuff, but I can read
// here files like it is node.js! Welcome to Electron world :)
console.log('The author of this app is:', appDir.read('package.json', 'json').author);

var tldrIndex;

request('http://tldr-pages.github.io/assets/index.json', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage.
    tldrIndex = JSON.parse(body);
    jetpack.write('offline-index.json', tldrIndex);
  }else{
    //fallback to offline index if cannot retrieve index from internet
    tldrIndex = appDir.read('offline-index.json', 'json')
  }
});

document.addEventListener('DOMContentLoaded', function () {

    document.getElementById('search-command-input').addEventListener("focus",function(){
        document.getElementsByClassName('app')[0].className = 'app active';
    });

    document.getElementById('list-all-commands').addEventListener("click",function(){
        document.getElementsByClassName('app')[0].className = 'app active';
    });

    document.getElementById('go-to-random-command').addEventListener("click",function(){
        document.getElementsByClassName('app')[0].className = 'app active';
    });

    //document.getElementById('greet').innerHTML = greet();
    //document.getElementById('platform-info').innerHTML = os.platform();
    //document.getElementById('env-name').innerHTML = env.name;
});

function search(){
    var commandToQuery = document.getElementById('search-command-input').value;
    console.log('commandToQuery',commandToQuery);
    if(commandToQuery === ''){
        listAllCommands();
    }
    findIndex(commandToQuery)
}

function findIndex(commandToQuery){
   var result =  tldrIndex.commands.find(function(command){ return command.name === commandToQuery });
   console.log(result);
   if(result){
       console.log('Command is found in the index. Try to retrieve result from filesystem');
       retrieveCommandDescription(result);
   }else{
       console.log('Command is not found in the index. Break');
       let filtered = tldrIndex.commands.filter(function(command){ return command.name.startsWith( commandToQuery )});
       listFilteredCommands(filtered);
   }
}

function listFilteredCommands( filteredCommands ){
    var template = Handlebars.compile(appDir.read('commandList.hbs'));
    document.getElementById('command-content').innerHTML = template({commands: filteredCommands});
}

function retrieveCommandDescription(commandObj){
    var description = appDir.read(`./pages/${commandObj.platform[0]}/${commandObj.name}.md`);
    console.log(description);
    var converter = new showdown.Converter();
    var descriptionConverted = converter.makeHtml(description);
    document.getElementById('command-content').scrollTop = 0;
    document.getElementById('command-content').innerHTML = descriptionConverted;
    document.getElementById('command-content').insertAdjacentHTML("afterbegin", `<button onclick='listAllCommands("${commandObj.name}")'><-</button>`);
}

function listAllCommands(jumpToCommand){
    var template = Handlebars.compile(appDir.read('commandList.hbs'));
    document.getElementById('command-content').innerHTML = template(tldrIndex);

    if(jumpToCommand){
        var targetCommand = document.getElementById(jumpToCommand);
        var top = targetCommand.offsetTop; //Getting Y of target element
        document.getElementById('command-content').scrollTop = top - 150;
        //window.scrollTo(0, top - 50);

        targetCommand.parentNode.className = 'active';
        setTimeout(function(){ targetCommand.parentNode.className = ''; }, 500);
    }
    //console.log( template(tldrIndex) ) ;
}

function randomCommand(){
    var commandIndex = getRandomInt(0, tldrIndex.commands.length - 1);
    retrieveCommandDescription(tldrIndex.commands[commandIndex]);
}

//From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function updateDatabase(){
    //What event is triggered when EOF is reached while writing to a stream ?
    //http://stackoverflow.com/questions/13156243/event-associated-with-fs-createwritestream-in-node-js
    var w = appDir.createWriteStream('tldr.zip');
    var downloadZip = request('http://tldr-pages.github.io/assets/tldr.zip').pipe( w );

    w.on('finish',function(){
     var zip = new AdmZip("tldr.zip");
     zip.extractAllToAsync(/*target path*/"./", /*overwrite*/true, function(){
         alert('update database completed!');
     });
    });
}<commit_msg>fix zip extraction's path in packaged app<commit_after>// Here is the starting point for your application code.
// All stuff below is just to show you how it works. You can delete all of it.

// Use new ES6 modules syntax for everything.
/*import os from 'os'; // native node.js module
import { remote } from 'electron'; // native electron module
import jetpack from 'fs-jetpack'; // module loaded from npm
import { greet } from './hello_world/hello_world'; // code authored by you in this project
import env from './env';*/

const os = require('os');
const electron = require('electron');
const { remote } = electron;
const jetpack = require('fs-jetpack');
const request = require('request');
const showdown = require('showdown');
const Handlebars = require('handlebars');
const AdmZip = require('adm-zip');

var app = remote.app;
var appDir = jetpack.cwd(app.getAppPath());

const {webFrame} = electron;
webFrame.setZoomFactor(1.4);

// Holy crap! This is browser window with HTML and stuff, but I can read
// here files like it is node.js! Welcome to Electron world :)
console.log('The author of this app is:', appDir.read('package.json', 'json').author);

var tldrIndex;

request('http://tldr-pages.github.io/assets/index.json', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage.
    tldrIndex = JSON.parse(body);
    jetpack.write('offline-index.json', tldrIndex);
  }else{
    //fallback to offline index if cannot retrieve index from internet
    tldrIndex = appDir.read('offline-index.json', 'json')
  }
});

document.addEventListener('DOMContentLoaded', function () {

    document.getElementById('search-command-input').addEventListener("focus",function(){
        document.getElementsByClassName('app')[0].className = 'app active';
    });

    document.getElementById('list-all-commands').addEventListener("click",function(){
        document.getElementsByClassName('app')[0].className = 'app active';
    });

    document.getElementById('go-to-random-command').addEventListener("click",function(){
        document.getElementsByClassName('app')[0].className = 'app active';
    });

    //document.getElementById('greet').innerHTML = greet();
    //document.getElementById('platform-info').innerHTML = os.platform();
    //document.getElementById('env-name').innerHTML = env.name;
});

function search(){
    var commandToQuery = document.getElementById('search-command-input').value;
    console.log('commandToQuery',commandToQuery);
    if(commandToQuery === ''){
        listAllCommands();
    }
    findIndex(commandToQuery)
}

function findIndex(commandToQuery){
   var result =  tldrIndex.commands.find(function(command){ return command.name === commandToQuery });
   console.log(result);
   if(result){
       console.log('Command is found in the index. Try to retrieve result from filesystem');
       retrieveCommandDescription(result);
   }else{
       console.log('Command is not found in the index. Break');
       let filtered = tldrIndex.commands.filter(function(command){ return command.name.startsWith( commandToQuery )});
       listFilteredCommands(filtered);
   }
}

function listFilteredCommands( filteredCommands ){
    var template = Handlebars.compile(appDir.read('commandList.hbs'));
    document.getElementById('command-content').innerHTML = template({commands: filteredCommands});
}

function retrieveCommandDescription(commandObj){
    var description = appDir.read(`./pages/${commandObj.platform[0]}/${commandObj.name}.md`);
    console.log(description);
    var converter = new showdown.Converter();
    var descriptionConverted = converter.makeHtml(description);
    document.getElementById('command-content').scrollTop = 0;
    document.getElementById('command-content').innerHTML = descriptionConverted;
    document.getElementById('command-content').insertAdjacentHTML("afterbegin", `<button onclick='listAllCommands("${commandObj.name}")'><-</button>`);
}

function listAllCommands(jumpToCommand){
    var template = Handlebars.compile(appDir.read('commandList.hbs'));
    document.getElementById('command-content').innerHTML = template(tldrIndex);

    if(jumpToCommand){
        var targetCommand = document.getElementById(jumpToCommand);
        var top = targetCommand.offsetTop; //Getting Y of target element
        document.getElementById('command-content').scrollTop = top - 150;
        //window.scrollTo(0, top - 50);

        targetCommand.parentNode.className = 'active';
        setTimeout(function(){ targetCommand.parentNode.className = ''; }, 500);
    }
    //console.log( template(tldrIndex) ) ;
}

function randomCommand(){
    var commandIndex = getRandomInt(0, tldrIndex.commands.length - 1);
    retrieveCommandDescription(tldrIndex.commands[commandIndex]);
}

//From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function updateDatabase(){
    //What event is triggered when EOF is reached while writing to a stream ?
    //http://stackoverflow.com/questions/13156243/event-associated-with-fs-createwritestream-in-node-js
    var w = appDir.createWriteStream('tldr.zip');
    var downloadZip = request('http://tldr-pages.github.io/assets/tldr.zip').pipe( w );

    w.on('finish',function(){
     var zip;
     if( process.platform === 'win32'){
       zip =  new AdmZip( app.getAppPath()+"\\tldr.zip" );
     }else{
       zip = new AdmZip( app.getAppPath()+"/tldr.zip" );
     }

     zip.extractAllToAsync( app.getAppPath() , /*overwrite*/true, function(){
         alert('update database completed!');
     });
    });
}<|endoftext|>


<commit_before>/*eslint-env node:true, node*/

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

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

var port = process.env.PORT | process.env.VCAP_APP_PORT || 3000;

app.listen(port);<commit_msg>change  back<commit_after>/*eslint-env node:true, node*/

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

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

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

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


<commit_before>/*
 * Copyright 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

/* jshint node: true, devel: true */
'use strict';

const
  bodyParser = require('body-parser'),
  cloudinary = require('cloudinary'),
  config = require('config'),
  crypto = require('crypto'),
  express = require('express'),
  https = require('https'),
  request = require('request');

var app = express();

app.set('port', process.env.PORT || 5000);
app.use(bodyParser.json({ verify: verifyRequestSignature }));
app.use(express.static('public'));

/*
 * Be sure to setup your config values before running this code. You can
 * set them using environment variables or modifying the config file in /config.
 *
 */

// App Secret can be retrieved from the App Dashboard
const APP_SECRET = (process.env.MESSENGER_APP_SECRET) ?
  process.env.MESSENGER_APP_SECRET :
  config.get('appSecret');

// Arbitrary value used to validate a webhook
const VALIDATION_TOKEN = (process.env.MESSENGER_VALIDATION_TOKEN) ?
  (process.env.MESSENGER_VALIDATION_TOKEN) :
  config.get('validationToken');

// Generate a page access token for your page from the App Dashboard
const PAGE_ACCESS_TOKEN = (process.env.MESSENGER_PAGE_ACCESS_TOKEN) ?
  (process.env.MESSENGER_PAGE_ACCESS_TOKEN) :
  config.get('pageAccessToken');

if (!(APP_SECRET && VALIDATION_TOKEN && PAGE_ACCESS_TOKEN)) {
  console.error("Missing config values");
  process.exit(1);
}

/*
 * Use your own validation token. Check that the token used in the Webhook
 * setup is the same token used here.
 *
 */
app.get('/webhook', function(req, res) {
  if (req.query['hub.mode'] === 'subscribe' &&
      req.query['hub.verify_token'] === VALIDATION_TOKEN) {
    console.log("Validating webhook");
    res.status(200).send(req.query['hub.challenge']);
  } else {
    console.error("Failed validation. Make sure the validation tokens match.");
    res.sendStatus(403);
  }
});

/*
 * All callbacks for Messenger are POST-ed. They will be sent to the same
 * webhook. Be sure to subscribe your app to your page to receive callbacks
 * for your page.
 * https://developers.facebook.com/docs/messenger-platform/implementation#subscribe_app_pages
 *
 */
app.post('/webhook', function (req, res) {
  var data = req.body;

  // Make sure this is a page subscription
  if (data.object == 'page') {
    // Iterate over each entry
    // There may be multiple if batched
    data.entry.forEach(function(pageEntry) {
      var pageID = pageEntry.id;
      var timeOfEvent = pageEntry.time;

      // Iterate over each messaging event
      pageEntry.messaging.forEach(function(messagingEvent) {
        if (messagingEvent.optin) {
          receivedAuthentication(messagingEvent);
        } else if (messagingEvent.message) {
          receivedMessage(messagingEvent);
        } else if (messagingEvent.delivery) {
          receivedDeliveryConfirmation(messagingEvent);
        } else if (messagingEvent.postback) {
          receivedPostback(messagingEvent);
        } else {
          console.log("Webhook received unknown messagingEvent: ", messagingEvent);
        }
      });
    });

    // Assume all went well.
    //
    // You must send back a 200, within 20 seconds, to let us know you've
    // successfully received the callback. Otherwise, the request will time out.
    res.sendStatus(200);
  }
});

/*
 * Verify that the callback came from Facebook. Using the App Secret from
 * the App Dashboard, we can verify the signature that is sent with each
 * callback in the x-hub-signature field, located in the header.
 *
 * https://developers.facebook.com/docs/graph-api/webhooks#setup
 *
 */
function verifyRequestSignature(req, res, buf) {
  var signature = req.headers["x-hub-signature"];

  if (!signature) {
    // For testing, let's log an error. In production, you should throw an
    // error.
    console.error("Couldn't validate the signature.");
  } else {
    var elements = signature.split('=');
    var method = elements[0];
    var signatureHash = elements[1];

    var expectedHash = crypto.createHmac('sha1', APP_SECRET)
                        .update(buf)
                        .digest('hex');

    if (signatureHash != expectedHash) {
      throw new Error("Couldn't validate the request signature.");
    }
  }
}

/*
 * Authorization Event
 *
 * The value for 'optin.ref' is defined in the entry point. For the "Send to
 * Messenger" plugin, it is the 'data-ref' field. Read more at
 * https://developers.facebook.com/docs/messenger-platform/webhook-reference#auth
 *
 */
function receivedAuthentication(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfAuth = event.timestamp;

  // The 'ref' field is set in the 'Send to Messenger' plugin, in the 'data-ref'
  // The developer can set this to an arbitrary value to associate the
  // authentication callback with the 'Send to Messenger' click event. This is
  // a way to do account linking when the user clicks the 'Send to Messenger'
  // plugin.
  var passThroughParam = event.optin.ref;

  console.log("Received authentication for user %d and page %d with pass " +
    "through param '%s' at %d", senderID, recipientID, passThroughParam,
    timeOfAuth);

  // When an authentication is received, we'll send a message back to the sender
  // to let them know it was successful.
  sendTextMessage(senderID, "Authentication successful");
}

/*
 * Message Event
 *
 * This event is called when a message is sent to your page. The 'message'
 * object format can vary depending on the kind of message that was received.
 * Read more at https://developers.facebook.com/docs/messenger-platform/webhook-reference#received_message
 *
 * For this example, we're going to echo any text that we get. If we get some
 * special keywords ('button', 'generic', 'receipt'), then we'll send back
 * examples of those bubbles to illustrate the special message bubbles we've
 * created. If we receive a message with an attachment (image, video, audio),
 * then we'll simply confirm that we've received the attachment.
 *
 */
function receivedMessage(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfMessage = event.timestamp;
  var message = event.message;

  console.log("Received message for user %d and page %d at %d with message:",
    senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  var messageId = message.mid;

  // You may get a text or attachment but not both
  var messageText = message.text;
  var messageAttachments = message.attachments;

  if (messageText) {

    // If we receive a text message, check to see if it matches any special
    // keywords and send back the corresponding example. Otherwise, just echo
    // the text we received.
    switch (messageText) {
      case 'image':
        sendImageMessage(senderID);
        break;

      case 'button':
        sendButtonMessage(senderID);
        break;

      default:
        sendHelpMessage(senderID);
        break;
    }
  } else if (messageAttachments) {
    sendTextMessage(senderID, "Message with attachment(s) received");
    var first_attachment = messageAttachments[0];
    if (first_attachment.type === 'image') {
      var image_url = first_attachment.payload.url;
      cloudinary.uploader.upload(image_url,
        function(result) {
          sendTextMessage(senderID, "URL: "
            + result.url
            + "\nSecure URL: "
            + result.secure_url);
        },
        { public_id: senderID }
      )
    }
  }
}

/*
 * Delivery Confirmation Event
 *
 * This event is sent to confirm the delivery of a message. Read more about
 * these fields at https://developers.facebook.com/docs/messenger-platform/webhook-reference#message_delivery
 *
 */
function receivedDeliveryConfirmation(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var delivery = event.delivery;
  var messageIDs = delivery.mids;
  var watermark = delivery.watermark;
  var sequenceNumber = delivery.seq;

  if (messageIDs) {
    messageIDs.forEach(function(messageID) {
      console.log("Received delivery confirmation for message ID: %s",
        messageID);
    });
  }

  console.log("All message before %d were delivered.", watermark);
}

/*
 * Postback Event
 *
 * This event is called when a postback is tapped on a Structured Message. Read
 * more at https://developers.facebook.com/docs/messenger-platform/webhook-reference#postback
 *
 */
function receivedPostback(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfPostback = event.timestamp;

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

  console.log("Received postback for user %d and page %d with payload '%s' " +
    "at %d", senderID, recipientID, payload, timeOfPostback);

  // When a postback is called, we'll send a message back to the sender to
  // let them know it was successful
  sendTextMessage(senderID, "Postback called");
}

/*
 * Send a message with an using the Send API.
 *
 */
function sendImageMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: "image",
        payload: {
          url: "http://i.imgur.com/zYIlgBl.png"
        }
      }
    }
  };

  callSendAPI(messageData);
}

/*
 * Send a text message using the Send API.
 *
 */
function sendHelpMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: "Send an image to get started.\n"
          + "Write top <text> or bottom <text> to set text."
    }
  };

  callSendAPI(messageData);
}

/*
 * Send a text message using the Send API.
 *
 */
function sendTextMessage(recipientId, messageText) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText
    }
  };

  callSendAPI(messageData);
}

/*
 * Send a button message using the Send API.
 *
 */
function sendButtonMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: "template",
        payload: {
          template_type: "button",
          text: "This is test text",
          buttons:[{
            type: "web_url",
            url: "https://www.oculus.com/en-us/rift/",
            title: "Open Web URL"
          }, {
            type: "postback",
            title: "Call Postback",
            payload: "Developer defined postback"
          }]
        }
      }
    }
  };

  callSendAPI(messageData);
}

/*
 * Call the Send API. The message data goes in the body. If successful, we'll
 * get the message id in a response
 *
 */
function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Successfully sent generic message with id %s to recipient %s",
        messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

// Start server
// Webhooks must be available via SSL with a certificate signed by a valid
// certificate authority.
app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

module.exports = app;

<commit_msg>Use cloudinary v2<commit_after>/*
 * Copyright 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

/* jshint node: true, devel: true */
'use strict';

const
  bodyParser = require('body-parser'),
  cloudinary = require('cloudinary'),
  config = require('config'),
  crypto = require('crypto'),
  express = require('express'),
  https = require('https'),
  request = require('request');

var app = express();

app.set('port', process.env.PORT || 5000);
app.use(bodyParser.json({ verify: verifyRequestSignature }));
app.use(express.static('public'));

/*
 * Be sure to setup your config values before running this code. You can
 * set them using environment variables or modifying the config file in /config.
 *
 */

// App Secret can be retrieved from the App Dashboard
const APP_SECRET = (process.env.MESSENGER_APP_SECRET) ?
  process.env.MESSENGER_APP_SECRET :
  config.get('appSecret');

// Arbitrary value used to validate a webhook
const VALIDATION_TOKEN = (process.env.MESSENGER_VALIDATION_TOKEN) ?
  (process.env.MESSENGER_VALIDATION_TOKEN) :
  config.get('validationToken');

// Generate a page access token for your page from the App Dashboard
const PAGE_ACCESS_TOKEN = (process.env.MESSENGER_PAGE_ACCESS_TOKEN) ?
  (process.env.MESSENGER_PAGE_ACCESS_TOKEN) :
  config.get('pageAccessToken');

if (!(APP_SECRET && VALIDATION_TOKEN && PAGE_ACCESS_TOKEN)) {
  console.error("Missing config values");
  process.exit(1);
}

/*
 * Use your own validation token. Check that the token used in the Webhook
 * setup is the same token used here.
 *
 */
app.get('/webhook', function(req, res) {
  if (req.query['hub.mode'] === 'subscribe' &&
      req.query['hub.verify_token'] === VALIDATION_TOKEN) {
    console.log("Validating webhook");
    res.status(200).send(req.query['hub.challenge']);
  } else {
    console.error("Failed validation. Make sure the validation tokens match.");
    res.sendStatus(403);
  }
});

/*
 * All callbacks for Messenger are POST-ed. They will be sent to the same
 * webhook. Be sure to subscribe your app to your page to receive callbacks
 * for your page.
 * https://developers.facebook.com/docs/messenger-platform/implementation#subscribe_app_pages
 *
 */
app.post('/webhook', function (req, res) {
  var data = req.body;

  // Make sure this is a page subscription
  if (data.object == 'page') {
    // Iterate over each entry
    // There may be multiple if batched
    data.entry.forEach(function(pageEntry) {
      var pageID = pageEntry.id;
      var timeOfEvent = pageEntry.time;

      // Iterate over each messaging event
      pageEntry.messaging.forEach(function(messagingEvent) {
        if (messagingEvent.optin) {
          receivedAuthentication(messagingEvent);
        } else if (messagingEvent.message) {
          receivedMessage(messagingEvent);
        } else if (messagingEvent.delivery) {
          receivedDeliveryConfirmation(messagingEvent);
        } else if (messagingEvent.postback) {
          receivedPostback(messagingEvent);
        } else {
          console.log("Webhook received unknown messagingEvent: ", messagingEvent);
        }
      });
    });

    // Assume all went well.
    //
    // You must send back a 200, within 20 seconds, to let us know you've
    // successfully received the callback. Otherwise, the request will time out.
    res.sendStatus(200);
  }
});

/*
 * Verify that the callback came from Facebook. Using the App Secret from
 * the App Dashboard, we can verify the signature that is sent with each
 * callback in the x-hub-signature field, located in the header.
 *
 * https://developers.facebook.com/docs/graph-api/webhooks#setup
 *
 */
function verifyRequestSignature(req, res, buf) {
  var signature = req.headers["x-hub-signature"];

  if (!signature) {
    // For testing, let's log an error. In production, you should throw an
    // error.
    console.error("Couldn't validate the signature.");
  } else {
    var elements = signature.split('=');
    var method = elements[0];
    var signatureHash = elements[1];

    var expectedHash = crypto.createHmac('sha1', APP_SECRET)
                        .update(buf)
                        .digest('hex');

    if (signatureHash != expectedHash) {
      throw new Error("Couldn't validate the request signature.");
    }
  }
}

/*
 * Authorization Event
 *
 * The value for 'optin.ref' is defined in the entry point. For the "Send to
 * Messenger" plugin, it is the 'data-ref' field. Read more at
 * https://developers.facebook.com/docs/messenger-platform/webhook-reference#auth
 *
 */
function receivedAuthentication(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfAuth = event.timestamp;

  // The 'ref' field is set in the 'Send to Messenger' plugin, in the 'data-ref'
  // The developer can set this to an arbitrary value to associate the
  // authentication callback with the 'Send to Messenger' click event. This is
  // a way to do account linking when the user clicks the 'Send to Messenger'
  // plugin.
  var passThroughParam = event.optin.ref;

  console.log("Received authentication for user %d and page %d with pass " +
    "through param '%s' at %d", senderID, recipientID, passThroughParam,
    timeOfAuth);

  // When an authentication is received, we'll send a message back to the sender
  // to let them know it was successful.
  sendTextMessage(senderID, "Authentication successful");
}

/*
 * Message Event
 *
 * This event is called when a message is sent to your page. The 'message'
 * object format can vary depending on the kind of message that was received.
 * Read more at https://developers.facebook.com/docs/messenger-platform/webhook-reference#received_message
 *
 * For this example, we're going to echo any text that we get. If we get some
 * special keywords ('button', 'generic', 'receipt'), then we'll send back
 * examples of those bubbles to illustrate the special message bubbles we've
 * created. If we receive a message with an attachment (image, video, audio),
 * then we'll simply confirm that we've received the attachment.
 *
 */
function receivedMessage(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfMessage = event.timestamp;
  var message = event.message;

  console.log("Received message for user %d and page %d at %d with message:",
    senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  var messageId = message.mid;

  // You may get a text or attachment but not both
  var messageText = message.text;
  var messageAttachments = message.attachments;

  if (messageText) {

    // If we receive a text message, check to see if it matches any special
    // keywords and send back the corresponding example. Otherwise, just echo
    // the text we received.
    switch (messageText) {
      case 'image':
        sendImageMessage(senderID);
        break;

      case 'button':
        sendButtonMessage(senderID);
        break;

      default:
        sendHelpMessage(senderID);
        break;
    }
  } else if (messageAttachments) {
    sendTextMessage(senderID, "Message with attachment(s) received");
    var first_attachment = messageAttachments[0];
    if (first_attachment.type === 'image') {
      var image_url = first_attachment.payload.url;
      cloudinary.v2.uploader.upload(image_url,
        { public_id: senderID },
        function(error, result) {
          if (error !== null) {
            sendTextMessage(senderID, "Error: " + error);
          } else {
            sendTextMessage(senderID, "URL: "
              + result.url
              + "\nSecure URL: "
              + result.secure_url);
          }
        }
      )
    }
  }
}

/*
 * Delivery Confirmation Event
 *
 * This event is sent to confirm the delivery of a message. Read more about
 * these fields at https://developers.facebook.com/docs/messenger-platform/webhook-reference#message_delivery
 *
 */
function receivedDeliveryConfirmation(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var delivery = event.delivery;
  var messageIDs = delivery.mids;
  var watermark = delivery.watermark;
  var sequenceNumber = delivery.seq;

  if (messageIDs) {
    messageIDs.forEach(function(messageID) {
      console.log("Received delivery confirmation for message ID: %s",
        messageID);
    });
  }

  console.log("All message before %d were delivered.", watermark);
}

/*
 * Postback Event
 *
 * This event is called when a postback is tapped on a Structured Message. Read
 * more at https://developers.facebook.com/docs/messenger-platform/webhook-reference#postback
 *
 */
function receivedPostback(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfPostback = event.timestamp;

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

  console.log("Received postback for user %d and page %d with payload '%s' " +
    "at %d", senderID, recipientID, payload, timeOfPostback);

  // When a postback is called, we'll send a message back to the sender to
  // let them know it was successful
  sendTextMessage(senderID, "Postback called");
}

/*
 * Send a message with an using the Send API.
 *
 */
function sendImageMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: "image",
        payload: {
          url: "http://i.imgur.com/zYIlgBl.png"
        }
      }
    }
  };

  callSendAPI(messageData);
}

/*
 * Send a text message using the Send API.
 *
 */
function sendHelpMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: "Send an image to get started.\n"
          + "Write top <text> or bottom <text> to set text."
    }
  };

  callSendAPI(messageData);
}

/*
 * Send a text message using the Send API.
 *
 */
function sendTextMessage(recipientId, messageText) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText
    }
  };

  callSendAPI(messageData);
}

/*
 * Send a button message using the Send API.
 *
 */
function sendButtonMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: "template",
        payload: {
          template_type: "button",
          text: "This is test text",
          buttons:[{
            type: "web_url",
            url: "https://www.oculus.com/en-us/rift/",
            title: "Open Web URL"
          }, {
            type: "postback",
            title: "Call Postback",
            payload: "Developer defined postback"
          }]
        }
      }
    }
  };

  callSendAPI(messageData);
}

/*
 * Call the Send API. The message data goes in the body. If successful, we'll
 * get the message id in a response
 *
 */
function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Successfully sent generic message with id %s to recipient %s",
        messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

// Start server
// Webhooks must be available via SSL with a certificate signed by a valid
// certificate authority.
app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

module.exports = app;

<|endoftext|>


<commit_before>(function() {

    var module = angular.module('app', ['ui.bootstrap']);

    module.controller('oaksPopupCtrl', ['$scope', '$uibModalInstance',
        function($scope, $uibModalInstance) {
            $scope.ok = function () {
                $uibModalInstance.close();
             };
        }]);

    module.controller('mainCtrl', ['$scope', '$uibModal', function($scope, $uibModal){
        $scope.title="About Megan Chantosa...";
            var modalInstance = $uibModal.open({
              animation: true,
              templateUrl: 'oaks-popup.html',
              controller: 'oaksPopupCtrl',
              size: 'sm'
            });
    }]);
})();<commit_msg>Fixing size again...<commit_after>(function() {

    var module = angular.module('app', ['ui.bootstrap']);

    module.controller('oaksPopupCtrl', ['$scope', '$uibModalInstance',
        function($scope, $uibModalInstance) {
            $scope.ok = function () {
                $uibModalInstance.close();
             };
        }]);

    module.controller('mainCtrl', ['$scope', '$uibModal', function($scope, $uibModal){
        $scope.title="About Megan Chantosa...";
            var modalInstance = $uibModal.open({
              animation: true,
              templateUrl: 'oaks-popup.html',
              controller: 'oaksPopupCtrl',
              size: 'md'
            });
    }]);
})();
<|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 app = express();

app.set('view engine', 'ejs');
app.use(favicon(__dirname + '/app/assets/img/favicon.png'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

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

app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

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
        });
    });
}

app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
<commit_msg>Back to app folder<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 app = express();

app.set('view engine', 'ejs');
app.use(favicon(__dirname + '/app/assets/img/favicon.png'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

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

app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

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
        });
    });
}

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>var express = require('express');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer = require('multer');
var app = express();
var path = require('path');
var ejs = require('ejs');
var session = require('express-session');
var flash = require('connect-flash');
var config = require('./config');
process.env.uploadsrc = config.domain+'/uploadimg/';
var mongoose = require('mongoose');
if (process.env.NODE_ENV == 'dev') {
    process.env.uploadsrc=config.domain+'/wxms/uploadimg/';
    mongoose.connect('mongodb://115.159.93.161:27017/wxms');
} else {
  mongoose.connect('mongodb://115.159.93.161:27017/wxms');
}
var MongoStore = require('connect-mongo')(session);

app.use(session({
    resave: true,
    saveUninitialized: true,
    secret: 'wxmssession',
    key: 'wxmssession',//cookie name
    store: new MongoStore({mongooseConnection: mongoose.connection}),
    cookie: {maxAge: 1000 * 60 * 60 * 24 * 30}//30 days
}));

app.use(multer({
    dest: __dirname + '/public/wxms/uploadimg/',
    rename: function (fieldname, filename) {
        return filename;
    },
    onFileUploadStart: function (file, data) {
        console.log(file.originalname);
    },
    onFileUploadComplete: function (file) {
        console.log(file.fieldname + ' uploaded to  ' + file.path);
        console.log(' file.size  ' + (file.size/1024/1024).toFixed(1));
    }
}));

var index = require('./routes/index');
var login = require('./routes/user/login');
var logout = require('./routes/user/logout');

var addBtncom = require('./routes/btncom/addBtncom');
var deleteBtncom = require('./routes/btncom/deleteBtncom');
var getBtncomListByPageId = require('./routes/btncom/getBtncomListByPageId');
var getBtncom = require('./routes/btncom/getBtncom');
var updateBtncom = require('./routes/btncom/updateBtncom');

var getImgsByUser = require('./routes/imgs/getImgsByUser');
var upLoadImg = require('./routes/imgs/upLoadImg');
var getPubImgs = require('./routes/imgs/getPubImgs');
var deleteImg = require('./routes/imgs/deleteImg');

var getAudiosByUser = require('./routes/audio/getAudiosByUser');
var upLoadAudio= require('./routes/audio/upLoadAudio');
var getPubAudios = require('./routes/audio/getPubIAudios');
var deleteAudio = require('./routes/audio/deleteAudio');

var addProject = require('./routes/project/addProject');
var getProjectList = require('./routes/project/getProjectList');
var deleteProject = require('./routes/project/deleteProject');
var getProject = require('./routes/project/getProject');
var updateProjectState = require('./routes/project/updateProjectState');
var getProjectStateList = require('./routes/project/getProjectStateList');
var updateProjectViewTimes = require('./routes/project/updateProjectViewTimes');

var createHtml = require('./routes/view/createHtml');
var downLoadHtml = require('./routes/view/downLoadHtml');

var addTextcom = require('./routes/textcom/addTextcom');
var deleteTextcom = require('./routes/textcom/deleteTextcom');
var getTextcom = require('./routes/textcom/getTextcom');
var updateTextcom = require('./routes/textcom/updateTextcom');
var getTextcomListByPageId = require('./routes/textcom/getTextcomListByPageId');

var addPage = require('./routes/page/addPage');
var deletePage = require('./routes/page/deletePage');
var getPageList = require('./routes/page/getPageList');
var updatePage = require('./routes/page/updatePage');
var getPage = require('./routes/page/getPage');

var addImgcom = require('./routes/imgcom/addImgcom');
var deleteImgcom = require('./routes/imgcom/deleteImgcom');
var getImgcom = require('./routes/imgcom/getImgcom');
var getImgcomListByPageId = require('./routes/imgcom/getImgcomListByPageId');
var updateImgcom = require('./routes/imgcom/updateImgcom');

var addTplByUser = require('./routes/template/addTplByUser');
var getPubTpl = require('./routes/template/getPubTpl');
var getTplByUser = require('./routes/template/getTplByUser');
var generationPage = require('./routes/template/generationPage');
var deleteTemplate = require('./routes/template/deleteTemplate');
var getOneTpl = require('./routes/template/getOneTpl');

var addAudiocom = require('./routes/audiocom/addAudiocom');
var deleteAudiocom = require('./routes/audiocom/deleteAudiocom');
var updateAudiocom = require('./routes/audiocom/updateAudiocom');
var getAudiocomByprojectId = require('./routes/audiocom/getAudiocomByprojectId');

var preview = require('./routes/preview/preview');

var repeater = require('./routes/repeater');

var addWeiXinShare = require('./routes/weixinshare/addWeiXinShare');
var getWeiXinShareByProjectId = require('./routes/weixinshare/getWeiXinShareByProjectId');
var deleteWeiXinShare = require('./routes/weixinshare/deleteWeiXinShare');

var copyItem = require('./routes/copyItem');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
app.use(flash());
// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/wxms.ico'));
app.use(bodyParser.json({
    limit: '100mb'
}));
app.use(bodyParser.urlencoded({
    extended: true,
    limit: '100mb'
}));
app.use(cookieParser());
app.use(multer());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'vendor')));

app.use('/', index);
app.use('/index', index);
app.use('/login', login);
app.use('/logout', logout);

app.use('/getImgsByUser', getImgsByUser);
app.use('/upLoadImg', upLoadImg);
app.use('/getPubImgs', getPubImgs);

app.use('/getAudiosByUser', getAudiosByUser);
app.use('/upLoadAudio', upLoadAudio);
app.use('/getPubAudios', getPubAudios);
app.use('/deleteAudio', deleteAudio);

app.use('/addBtncom', addBtncom);
app.use('/deleteBtncom', deleteBtncom);
app.use('/getBtncomListByPageId', getBtncomListByPageId);
app.use('/getBtncom', getBtncom);
app.use('/updateBtncom', updateBtncom);

app.use('/addProject', addProject);
app.use('/getProjectList', getProjectList);
app.use('/deleteProject', deleteProject);
app.use('/getProject', getProject);
app.use('/updateProjectState', updateProjectState);
app.use('/getProjectStateList', getProjectStateList);
app.use('/updateProjectViewTimes', updateProjectViewTimes);

app.use('/addPage', addPage);
app.use('/deletePage', deletePage);
app.use('/getPageList', getPageList);
app.use('/updatePage', updatePage);
app.use('/getPage', getPage);

app.use('/createHtml', createHtml);
app.use('/downLoadHtml', downLoadHtml);

app.use('/addTextcom', addTextcom);
app.use('/deleteTextcom', deleteTextcom);
app.use('/getTextcom', getTextcom);
app.use('/updateTextcom', updateTextcom);
app.use('/getTextcomListByPageId', getTextcomListByPageId);

app.use('/addImgcom', addImgcom);
app.use('/deleteImgcom', deleteImgcom);
app.use('/getImgcom', getImgcom);
app.use('/getImgcomListByPageId', getImgcomListByPageId);
app.use('/updateImgcom', updateImgcom);
app.use('/deleteImg', deleteImg);

app.use('/addTplByUser',addTplByUser);
app.use('/getPubTpl',getPubTpl);
app.use('/getTplByUser',getTplByUser);
app.use('/deleteTemplate',deleteTemplate);
app.use('/generationPage',generationPage);
app.use('/getOneTpl',getOneTpl);

app.use('/addAudiocom', addAudiocom);
app.use('/deleteAudiocom', deleteAudiocom);
app.use('/updateAudiocom', updateAudiocom);
app.use('/getAudiocomByprojectId', getAudiocomByprojectId);

app.use('/show', preview);

app.use('/repeater', repeater);

app.use('/addWeiXinShare', addWeiXinShare);
app.use('/getWeiXinShareByProjectId', getWeiXinShareByProjectId);
app.use('/deleteWeiXinShare', deleteWeiXinShare);

app.use('/copyItem', copyItem);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(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>swich mongodb ip<commit_after>var express = require('express');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer = require('multer');
var app = express();
var path = require('path');
var ejs = require('ejs');
var session = require('express-session');
var flash = require('connect-flash');
var config = require('./config');
process.env.uploadsrc = config.domain+'/uploadimg/';
var mongoose = require('mongoose');
if (process.env.NODE_ENV == 'dev') {
    process.env.uploadsrc=config.domain+'/wxms/uploadimg/';
    mongoose.connect('mongodb://115.159.93.161:27017/wxms');
} else {
    mongoose.connect('mongodb://127.0.0.1:27017/wxms');
}
var MongoStore = require('connect-mongo')(session);

app.use(session({
    resave: true,
    saveUninitialized: true,
    secret: 'wxmssession',
    key: 'wxmssession',//cookie name
    store: new MongoStore({mongooseConnection: mongoose.connection}),
    cookie: {maxAge: 1000 * 60 * 60 * 24 * 30}//30 days
}));

app.use(multer({
    dest: __dirname + '/public/wxms/uploadimg/',
    rename: function (fieldname, filename) {
        return filename;
    },
    onFileUploadStart: function (file, data) {
        console.log(file.originalname);
    },
    onFileUploadComplete: function (file) {
        console.log(file.fieldname + ' uploaded to  ' + file.path);
        console.log(' file.size  ' + (file.size/1024/1024).toFixed(1));
    }
}));

var index = require('./routes/index');
var login = require('./routes/user/login');
var logout = require('./routes/user/logout');

var addBtncom = require('./routes/btncom/addBtncom');
var deleteBtncom = require('./routes/btncom/deleteBtncom');
var getBtncomListByPageId = require('./routes/btncom/getBtncomListByPageId');
var getBtncom = require('./routes/btncom/getBtncom');
var updateBtncom = require('./routes/btncom/updateBtncom');

var getImgsByUser = require('./routes/imgs/getImgsByUser');
var upLoadImg = require('./routes/imgs/upLoadImg');
var getPubImgs = require('./routes/imgs/getPubImgs');
var deleteImg = require('./routes/imgs/deleteImg');

var getAudiosByUser = require('./routes/audio/getAudiosByUser');
var upLoadAudio= require('./routes/audio/upLoadAudio');
var getPubAudios = require('./routes/audio/getPubIAudios');
var deleteAudio = require('./routes/audio/deleteAudio');

var addProject = require('./routes/project/addProject');
var getProjectList = require('./routes/project/getProjectList');
var deleteProject = require('./routes/project/deleteProject');
var getProject = require('./routes/project/getProject');
var updateProjectState = require('./routes/project/updateProjectState');
var getProjectStateList = require('./routes/project/getProjectStateList');
var updateProjectViewTimes = require('./routes/project/updateProjectViewTimes');

var createHtml = require('./routes/view/createHtml');
var downLoadHtml = require('./routes/view/downLoadHtml');

var addTextcom = require('./routes/textcom/addTextcom');
var deleteTextcom = require('./routes/textcom/deleteTextcom');
var getTextcom = require('./routes/textcom/getTextcom');
var updateTextcom = require('./routes/textcom/updateTextcom');
var getTextcomListByPageId = require('./routes/textcom/getTextcomListByPageId');

var addPage = require('./routes/page/addPage');
var deletePage = require('./routes/page/deletePage');
var getPageList = require('./routes/page/getPageList');
var updatePage = require('./routes/page/updatePage');
var getPage = require('./routes/page/getPage');

var addImgcom = require('./routes/imgcom/addImgcom');
var deleteImgcom = require('./routes/imgcom/deleteImgcom');
var getImgcom = require('./routes/imgcom/getImgcom');
var getImgcomListByPageId = require('./routes/imgcom/getImgcomListByPageId');
var updateImgcom = require('./routes/imgcom/updateImgcom');

var addTplByUser = require('./routes/template/addTplByUser');
var getPubTpl = require('./routes/template/getPubTpl');
var getTplByUser = require('./routes/template/getTplByUser');
var generationPage = require('./routes/template/generationPage');
var deleteTemplate = require('./routes/template/deleteTemplate');
var getOneTpl = require('./routes/template/getOneTpl');

var addAudiocom = require('./routes/audiocom/addAudiocom');
var deleteAudiocom = require('./routes/audiocom/deleteAudiocom');
var updateAudiocom = require('./routes/audiocom/updateAudiocom');
var getAudiocomByprojectId = require('./routes/audiocom/getAudiocomByprojectId');

var preview = require('./routes/preview/preview');

var repeater = require('./routes/repeater');

var addWeiXinShare = require('./routes/weixinshare/addWeiXinShare');
var getWeiXinShareByProjectId = require('./routes/weixinshare/getWeiXinShareByProjectId');
var deleteWeiXinShare = require('./routes/weixinshare/deleteWeiXinShare');

var copyItem = require('./routes/copyItem');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
app.use(flash());
// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/wxms.ico'));
app.use(bodyParser.json({
    limit: '100mb'
}));
app.use(bodyParser.urlencoded({
    extended: true,
    limit: '100mb'
}));
app.use(cookieParser());
app.use(multer());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'vendor')));

app.use('/', index);
app.use('/index', index);
app.use('/login', login);
app.use('/logout', logout);

app.use('/getImgsByUser', getImgsByUser);
app.use('/upLoadImg', upLoadImg);
app.use('/getPubImgs', getPubImgs);

app.use('/getAudiosByUser', getAudiosByUser);
app.use('/upLoadAudio', upLoadAudio);
app.use('/getPubAudios', getPubAudios);
app.use('/deleteAudio', deleteAudio);

app.use('/addBtncom', addBtncom);
app.use('/deleteBtncom', deleteBtncom);
app.use('/getBtncomListByPageId', getBtncomListByPageId);
app.use('/getBtncom', getBtncom);
app.use('/updateBtncom', updateBtncom);

app.use('/addProject', addProject);
app.use('/getProjectList', getProjectList);
app.use('/deleteProject', deleteProject);
app.use('/getProject', getProject);
app.use('/updateProjectState', updateProjectState);
app.use('/getProjectStateList', getProjectStateList);
app.use('/updateProjectViewTimes', updateProjectViewTimes);

app.use('/addPage', addPage);
app.use('/deletePage', deletePage);
app.use('/getPageList', getPageList);
app.use('/updatePage', updatePage);
app.use('/getPage', getPage);

app.use('/createHtml', createHtml);
app.use('/downLoadHtml', downLoadHtml);

app.use('/addTextcom', addTextcom);
app.use('/deleteTextcom', deleteTextcom);
app.use('/getTextcom', getTextcom);
app.use('/updateTextcom', updateTextcom);
app.use('/getTextcomListByPageId', getTextcomListByPageId);

app.use('/addImgcom', addImgcom);
app.use('/deleteImgcom', deleteImgcom);
app.use('/getImgcom', getImgcom);
app.use('/getImgcomListByPageId', getImgcomListByPageId);
app.use('/updateImgcom', updateImgcom);
app.use('/deleteImg', deleteImg);

app.use('/addTplByUser',addTplByUser);
app.use('/getPubTpl',getPubTpl);
app.use('/getTplByUser',getTplByUser);
app.use('/deleteTemplate',deleteTemplate);
app.use('/generationPage',generationPage);
app.use('/getOneTpl',getOneTpl);

app.use('/addAudiocom', addAudiocom);
app.use('/deleteAudiocom', deleteAudiocom);
app.use('/updateAudiocom', updateAudiocom);
app.use('/getAudiocomByprojectId', getAudiocomByprojectId);

app.use('/show', preview);

app.use('/repeater', repeater);

app.use('/addWeiXinShare', addWeiXinShare);
app.use('/getWeiXinShareByProjectId', getWeiXinShareByProjectId);
app.use('/deleteWeiXinShare', deleteWeiXinShare);

app.use('/copyItem', copyItem);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(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>var app = require('./config/express')(); // passo local do express e executo a funcao anonima
var http = require('http').Server(app);
var io = require('socket.io')(http);

//app.set('io', io);

console.log(io);

app.io = io; //configura o socoket.io dentro do express

var porta = process.env.PORT || 3000;
var server = http.listen(porta, function () {

	var host = server.address().address;
	var port = server.address().port;

	console.log('era-uma-vez listening at http://%s:%s', host, port);

});
/*

io.on('connection', function (socket) {
	app.set('socketClient', socket);
	//socket.emit('connection', {message: "You are connected!"});
});*/<commit_msg>changes<commit_after>var app = require('./config/express')(); // passo local do express e executo a funcao anonima
var http = require('http').Server(app);
var io = require('socket.io')(http);

//app.set('io', io);

app.io = io; //configura o socoket.io dentro do express

var porta = process.env.PORT || 3000;
var server = http.listen(porta, function () {

	var host = server.address().address;
	var port = server.address().port;

	console.log('era-uma-vez listening at http://%s:%s', host, port);

});
/*

io.on('connection', function (socket) {
	app.set('socketClient', socket);
	//socket.emit('connection', {message: "You are connected!"});
});*/<|endoftext|>


<commit_before>const express = require('express');
const compression = require('compression');
const app = express();

const PORT = process.env.PORT || 3000;

app.use(compression());
app.use(express.static(`${__dirname}/public`));
//app.use('/', require('./src/index'));

app.get('*', function (req, res) {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.listen(PORT);<commit_msg>Adding missing require('path')<commit_after>const express = require('express');
const compression = require('compression');
const app = express();
const path = require('path');

const PORT = process.env.PORT || 3000;

app.use(compression());
app.use(express.static(`${__dirname}/public`));
//app.use('/', require('./src/index'));

app.get('*', function (req, res) {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

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