<commit_before>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');
// var d       = require('./twitterData.js');
//
var envVars = "";

if (!process.env.TWITTER_CONSUMER_KEY) {
  envVars = require("./envVars.js");
  envVars.add();
}

var d = {
  html: [],
  rawTweets: [],
  getData: function (req, res, spec) {
    var Twitter = require("twitter");

    var client = new Twitter({
      consumer_key: process.env.TWITTER_CONSUMER_KEY,
      consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
      access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
      access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
    });

    var geocode = spec ? spec : '40.7207919,-74.0007582,0.5km';

    var now = new Date(),
      year = now.getFullYear(),
      month = now.getMonth() + 1, // js months are zero based
      day = now.getDate() - 2,    // only show day old tweets
      twoDaysAgo = year + "-" + month + "-" + day;

    /*
     *  geocode: lat,lon,radius
     *  count: defaults to 15, max is 100
     *  result_type: recent, popular, mixed
     *  until: 2012-09-01 // tweets before date
     */
    var options = {
      geocode: geocode,
      count: 100,
      until: twoDaysAgo
    };

    client.get('search/tweets', options, function(error, params,
        response){

      var tweetList = [],
        tweetHtml = "",
        rawTweet,
        newTweet,
        results;

      if (error) {
        console.log("error: " + JSON.stringify(error));
        console.log();
        throw error;
      }

      if (params && params.hasOwnProperty("statuses")) {
        results = params.statuses;

        d.rawTweets = results;

        for (var i = 0, l = results.length; i < l; i++) {
          rawTweet = results[i];

          // d.getTweetWidget(req, res, rawTweet.id_str);
          newTweet = {
            id          : rawTweet.id_str,
            lat         : rawTweet.geo.coordinates[0],
            lon         : rawTweet.geo.coordinates[1],
            text        : rawTweet.text,
            datetime    : rawTweet.created_at,
            screen_name : rawTweet.user.screen_name
          };

          tweetHtml += "
" +
              "
latitude: " + newTweet.lat + "
" +
              "
longitude: "+ newTweet.lon + "
" +
              "
text: "+ newTweet.text + "
" +
              "
date: "+ newTweet.datetime + "
" +
              "
screen_name: "+ newTweet.screen_name + "
" +
              "
";

          tweetList[i] = newTweet;
        }

        res.setHeader('Content-Type', 'text/html');
        res.send("" +
            "" +
            "" + tweetHtml + "");
        // res.send(JSON.stringify(tweetList));

      } else {
        res.setHeader('Content-Type', 'text/html');
        res.send("fail");
      }
      // console.log(JSON.stringify(response));  // Raw response object.?
    });
  },
  getTweetWidget: function (req, res, tweetId) {
    var Twitter = require("twitter");

    var client = new Twitter({
      consumer_key: process.env.TWITTER_CONSUMER_KEY,
      consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
      access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
      access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
    });

    client.get('statuses/oembed', {id: tweetId}, function(error, params,
      response){

        if (error) {
          console.log(error);
        }

        if (params) {
          d.html.push(params.html);

          if (d.html.length === d.rawTweets.length) {
            console.log("show me some html");
            res.setHeader('Content-Type', 'text/html');
            res.send(d.html.join(""));
          }
        }

        if (response) {
          // console.log("response");
          // console.log(response);
        }

    });
  }
};

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ==============================================================  */
    /*  Helper functions.                                               */
    /*  ==============================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
      //  Set the environment variables we need.
      self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
      self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

      if (typeof self.ipaddress === "undefined") {
        //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
        //  allows us to run/test the app locally.
        console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');

        // use 0.0.0.0 when using vagrant vm, set in envVars.js
        self.ipaddress = "127.0.0.1";
      }
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
      if (typeof self.zcache === "undefined") {
        self.zcache = { 'varWeb.html': '' };
      }

      //  Local cache for static content.
      self.zcache['index.html'] = fs.readFileSync('./index.html');
      self.zcache['varWeb.html'] = fs.readFileSync('./varWeb.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from
     *  cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ==============================================================  */
    /*  App server functions (main app logic here).                     */
    /*  ==============================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = {};

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";

            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };

        self.routes['/varWeb'] = function(req, res) {
          res.setHeader('Content-Type', 'text/html');
          res.send(self.cache_get('varWeb.html') );
        };

        self.routes['/request'] = function(req, res) {
          // d.getData(req, res);
          console.log(req);
          console.log("test request");
          res.send("{t:'test'}");
        };

        self.routes['/test/:geocode'] = function(req, res) {
          console.log(req.params.geocode);
          d.getData(req, res, req.params.geocode);
        };

    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }

        // add subfolders -- needed to load js and css
        self.app.use("/css", express.static(__dirname + '/css'));
        self.app.use("/js", express.static(__dirname + '/js'));

    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();
<commit_msg>added tweets as json to page<commit_after>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');
// var d       = require('./twitterData.js');
//
var envVars = "";

if (!process.env.TWITTER_CONSUMER_KEY) {
  envVars = require("./envVars.js");
  envVars.add();
}

var d = {
  html: [],
  rawTweets: [],
  getData: function (req, res, spec) {
    var Twitter = require("twitter");

    var client = new Twitter({
      consumer_key: process.env.TWITTER_CONSUMER_KEY,
      consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
      access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
      access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
    });

    var geocode = spec ? spec : '40.7207919,-74.0007582,0.5km';

    var now = new Date(),
      year = now.getFullYear(),
      month = now.getMonth() + 1, // js months are zero based
      day = now.getDate() - 2,    // only show day old tweets
      twoDaysAgo = year + "-" + month + "-" + day;

    /*
     *  geocode: lat,lon,radius
     *  count: defaults to 15, max is 100
     *  result_type: recent, popular, mixed
     *  until: 2012-09-01 // tweets before date
     */
    var options = {
      geocode: geocode,
      count: 100,
      until: twoDaysAgo
    };

    client.get('search/tweets', options, function(error, params,
        response){

      var tweetList = [],
        tweetHtml = "",
        rawTweet,
        newTweet,
        results;

      if (error) {
        console.log("error: " + JSON.stringify(error));
        console.log();
        throw error;
      }

      if (params && params.hasOwnProperty("statuses")) {
        results = params.statuses;

        d.rawTweets = results;

        for (var i = 0, l = results.length; i < l; i++) {
          rawTweet = results[i];

          // d.getTweetWidget(req, res, rawTweet.id_str);
          newTweet = {
            id          : rawTweet.id_str,
            lat         : rawTweet.geo.coordinates[0],
            lon         : rawTweet.geo.coordinates[1],
            text        : rawTweet.text,
            datetime    : rawTweet.created_at,
            screen_name : rawTweet.user.screen_name
          };

          tweetHtml += "
" +
              "
latitude: " + newTweet.lat + "
" +
              "
longitude: "+ newTweet.lon + "
" +
              "
text: "+ newTweet.text + "
" +
              "
date: "+ newTweet.datetime + "
" +
              "
screen_name: "+ newTweet.screen_name + "
" +
              "
";

          tweetList[i] = newTweet;
        }

        res.setHeader('Content-Type', 'text/html');
        res.send("" +
            "" +
            "" + tweetHtml +
            "" +
            "");
        // res.send(JSON.stringify(tweetList));

      } else {
        res.setHeader('Content-Type', 'text/html');
        res.send("fail");
      }
      // console.log(JSON.stringify(response));  // Raw response object.?
    });
  },
  getTweetWidget: function (req, res, tweetId) {
    var Twitter = require("twitter");

    var client = new Twitter({
      consumer_key: process.env.TWITTER_CONSUMER_KEY,
      consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
      access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
      access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
    });

    client.get('statuses/oembed', {id: tweetId}, function(error, params,
      response){

        if (error) {
          console.log(error);
        }

        if (params) {
          d.html.push(params.html);

          if (d.html.length === d.rawTweets.length) {
            console.log("show me some html");
            res.setHeader('Content-Type', 'text/html');
            res.send(d.html.join(""));
          }
        }

        if (response) {
          // console.log("response");
          // console.log(response);
        }

    });
  }
};

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ==============================================================  */
    /*  Helper functions.                                               */
    /*  ==============================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
      //  Set the environment variables we need.
      self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
      self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

      if (typeof self.ipaddress === "undefined") {
        //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
        //  allows us to run/test the app locally.
        console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');

        // use 0.0.0.0 when using vagrant vm, set in envVars.js
        self.ipaddress = "127.0.0.1";
      }
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
      if (typeof self.zcache === "undefined") {
        self.zcache = { 'varWeb.html': '' };
      }

      //  Local cache for static content.
      self.zcache['index.html'] = fs.readFileSync('./index.html');
      self.zcache['varWeb.html'] = fs.readFileSync('./varWeb.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from
     *  cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ==============================================================  */
    /*  App server functions (main app logic here).                     */
    /*  ==============================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = {};

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";

            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };

        self.routes['/varWeb'] = function(req, res) {
          res.setHeader('Content-Type', 'text/html');
          res.send(self.cache_get('varWeb.html') );
        };

        self.routes['/request'] = function(req, res) {
          // d.getData(req, res);
          console.log(req);
          console.log("test request");
          res.send("{t:'test'}");
        };

        self.routes['/test/:geocode'] = function(req, res) {
          console.log(req.params.geocode);
          d.getData(req, res, req.params.geocode);
        };

    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }

        // add subfolders -- needed to load js and css
        self.app.use("/css", express.static(__dirname + '/css'));
        self.app.use("/js", express.static(__dirname + '/js'));

    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();
<|endoftext|>


<commit_before>var express = require('express');
var cors = require('cors');
var httpRequest = require('request');
var xmlParser = require('xml2js');
var path = require('path');
var app = express();
var router = express.Router();
var every = require('schedule').every;

var htmlDir = './html/';
var port = process.env.PORT || 8888;
// This is a demo key use environment if possible
var bartApiKey = process.env.BART_API_KEY || 'MW9S-E7SL-26DU-VV8V';

var stationsInfo = undefined;

var infoCache = {
	stationList : undefined,

	getStationList: function() {
		return stationList;
	},

	updateStationList: function(newStationList) {
		stationList = newStationList;
	},
};

loadStationList = function() {
	console.log('Refreshing Station List cache...');
	httpRequest({
		uri: 'http://api.bart.gov/api/stn.aspx?cmd=stns&key=' + bartApiKey,
		method: 'GET',
		timeout: 10000,
		followRedirect: true,
		maxRedirects: 10
	}, function(error, resp, body) {
		// TODO non-happy path
		xmlParser.parseString(body, { trim: true, explicitArray: false }, function(err, res) {
			infoCache.updateStationList(res.root.stations);
			console.log('Station List cache refreshed.');
		});
	});
};

getDistance = function(latUser, lonUser, latStation, lonStation) {
	var R = 6371;
	var dLat = (latStation - latUser).toRad();
	var dLon = (lonStation - lonUser).toRad();
	var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        	Math.cos(latStation.toRad()) * Math.cos(latUser.toRad()) *
        	Math.sin(dLon / 2) * Math.sin(dLon / 2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	var d = R * c;

	return d;
};

router.route('/').get(
	function(request, response) {
		response.sendFile('index.html', { root: path.join(__dirname, './html') });
	}
);

router.route('/status').get(
	function(request, response) {
		httpRequest({
			uri: 'http://api.bart.gov/api/bsa.aspx?cmd=count&key=' + bartApiKey,
			method: 'GET',
			timeout: 10000,
			followRedirect: true,
			maxRedirects: 10
		}, function(error, resp, body) {
			// TODO non-happy path
			var xmlStatus = xmlParser.parseString(body, { trim: true, explicitArray: false }, function(err, res) {
				response.jsonp(res.root);
			});
		});
	}
);

router.route('/stations').get(
	function(request, response) {
		response.jsonp(infoCache.getStationList().station);
	}
);

router.route('/station/:stationId').get(
	function(request, response) {
		var stations = infoCache.getStationList().station;

		for (var n = 0; n < stations.length; n++) {
			var thisStation = stations[n];
			if (thisStation.abbr === request.params.stationId) {
				response.jsonp(thisStation);
				break;
			}
		}
	}
);

// TODO make this real, return single closest station
router.route('/station/:latitude/:longitude').get(
	function(request, response) {
		var stations = infoCache.getStationList().station;
		var closestStationAbbr = "FTVL";

		for (var n = 0; n < stations.length; n++) {
			var thisStation = stations[n];
			if (thisStation.abbr === closestStationAbbr) {
				// TODO Add distance field!
				response.jsonp(thisStation);
				break;
			}
		}
	}
);

// TODO make this real, return all stations with distances and isClosest set
router.route('/stations/:latitude/:longitude').get(
	function(request, response) {
		var stations = infoCache.getStationList().station;
		var closestStationAbbr = "FTVL";

		// TODO sorting and stuff
		response.jsonp(infoCache.getStationList().station);
	}
);

// TODO work on station info
// http://api.bart.gov/api/stn.aspx?cmd=stninfo&orig=24th&key=MW9S-E7SL-26DU-VV8V

// TODO work on station access l=1 show legend, l=0 suppresses
// http://api.bart.gov/api/stn.aspx?cmd=stnaccess&orig=12th&key=MW9S-E7SL-26DU-VV8V&l=1

router.route('/departures/:stationId').get(
	function(request, response) {
		httpRequest({
			uri: 'http://api.bart.gov/api/etd.aspx?cmd=etd&orig=' + request.param('stationId') + '&key=' + bartApiKey,
			method: 'GET',
			timeout: 10000,
			followRedirect: true,
			maxRedirects: 10
		}, function(error, resp, body) {
			// TODO non-happy path
			var xmlStations = xmlParser.parseString(body, { trim: true, explicitArray: false }, function(err, res) {
				response.jsonp(res.root.station);
			});
		});
	}
);

// TODO Add the option to specify time/date?
router.route('/tickets/:fromStation/:toStation').get(
	function(request, response) {
		httpRequest({
			uri: 'http://api.bart.gov/api/sched.aspx?cmd=depart&orig=' + request.param('fromStation') + '&dest=' + request.param('toStation') + '&time=9:00am' + '&b=0&a=1&key=' + bartApiKey,
			method: 'GET',
			timeout: 10000,
			followRedirect: true,
			maxRedirects: 10
		}, function(error, resp, body) {
			// TODO non-happy path
			var xmlStations = xmlParser.parseString(body, { trim: true, explicitArray: false }, function(err, res) {
				response.jsonp(res.root);
			});
		});
	}
);

// Prime the station list on startup and read periodically
loadStationList();
every('24h').do(function() {
	loadStationList();
});

app.use(cors());
app.use('/api', router);
app.listen(port);
console.log('BART API Server listening on port ' + port);
<commit_msg>Added serviceAnnouncements endpoint<commit_after>var express = require('express');
var cors = require('cors');
var httpRequest = require('request');
var xmlParser = require('xml2js');
var path = require('path');
var app = express();
var router = express.Router();
var every = require('schedule').every;

var htmlDir = './html/';
var port = process.env.PORT || 8888;
// This is a demo key use environment if possible
var bartApiKey = process.env.BART_API_KEY || 'MW9S-E7SL-26DU-VV8V';

var stationsInfo = undefined;

var infoCache = {
	stationList : undefined,

	getStationList: function() {
		return stationList;
	},

	updateStationList: function(newStationList) {
		stationList = newStationList;
	},
};

loadStationList = function() {
	console.log('Refreshing Station List cache...');
	httpRequest({
		uri: 'http://api.bart.gov/api/stn.aspx?cmd=stns&key=' + bartApiKey,
		method: 'GET',
		timeout: 10000,
		followRedirect: true,
		maxRedirects: 10
	}, function(error, resp, body) {
		// TODO non-happy path
		xmlParser.parseString(body, { trim: true, explicitArray: false }, function(err, res) {
			infoCache.updateStationList(res.root.stations);
			console.log('Station List cache refreshed.');
		});
	});
};

getDistance = function(latUser, lonUser, latStation, lonStation) {
	var R = 6371;
	var dLat = (latStation - latUser).toRad();
	var dLon = (lonStation - lonUser).toRad();
	var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        	Math.cos(latStation.toRad()) * Math.cos(latUser.toRad()) *
        	Math.sin(dLon / 2) * Math.sin(dLon / 2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	var d = R * c;

	return d;
};

router.route('/').get(
	function(request, response) {
		response.sendFile('index.html', { root: path.join(__dirname, './html') });
	}
);

router.route('/status').get(
	function(request, response) {
		httpRequest({
			uri: 'http://api.bart.gov/api/bsa.aspx?cmd=count&key=' + bartApiKey,
			method: 'GET',
			timeout: 10000,
			followRedirect: true,
			maxRedirects: 10
		}, function(error, resp, body) {
			// TODO non-happy path
			var xmlStatus = xmlParser.parseString(body, { trim: true, explicitArray: false }, function(err, res) {
				response.jsonp(res.root);
			});
		});
	}
);

router.route('/serviceAnnouncements').get(
	function(request, response) {
		httpRequest({
			uri: 'http://api.bart.gov/api/bsa.aspx?cmd=bsa&date=today&key=' + bartApiKey,
			method: 'GET',
			timeout: 10000,
			followRedirect: true,
			maxRedirects: 10
		}, function(error, resp, body) {
			// TODO non happy path
			var xmlServiceAnnouncements = xmlParser.parseString(body, { trim: true, explicitArray: false }, function(err, res) {
				response.jsonp(res.root);
			});
		});
	}
);

router.route('/stations').get(
	function(request, response) {
		response.jsonp(infoCache.getStationList().station);
	}
);

router.route('/station/:stationId').get(
	function(request, response) {
		var stations = infoCache.getStationList().station;

		for (var n = 0; n < stations.length; n++) {
			var thisStation = stations[n];
			if (thisStation.abbr === request.params.stationId) {
				response.jsonp(thisStation);
				break;
			}
		}
	}
);

// TODO make this real, return single closest station
router.route('/station/:latitude/:longitude').get(
	function(request, response) {
		var stations = infoCache.getStationList().station;
		var closestStationAbbr = "FTVL";

		for (var n = 0; n < stations.length; n++) {
			var thisStation = stations[n];
			if (thisStation.abbr === closestStationAbbr) {
				// TODO Add distance field!
				response.jsonp(thisStation);
				break;
			}
		}
	}
);

// TODO make this real, return all stations with distances and isClosest set
router.route('/stations/:latitude/:longitude').get(
	function(request, response) {
		var stations = infoCache.getStationList().station;
		var closestStationAbbr = "FTVL";

		// TODO sorting and stuff
		response.jsonp(infoCache.getStationList().station);
	}
);

// TODO work on station info
// http://api.bart.gov/api/stn.aspx?cmd=stninfo&orig=24th&key=MW9S-E7SL-26DU-VV8V

// TODO work on station access l=1 show legend, l=0 suppresses
// http://api.bart.gov/api/stn.aspx?cmd=stnaccess&orig=12th&key=MW9S-E7SL-26DU-VV8V&l=1

router.route('/departures/:stationId').get(
	function(request, response) {
		httpRequest({
			uri: 'http://api.bart.gov/api/etd.aspx?cmd=etd&orig=' + request.param('stationId') + '&key=' + bartApiKey,
			method: 'GET',
			timeout: 10000,
			followRedirect: true,
			maxRedirects: 10
		}, function(error, resp, body) {
			// TODO non-happy path
			var xmlStations = xmlParser.parseString(body, { trim: true, explicitArray: false }, function(err, res) {
				response.jsonp(res.root.station);
			});
		});
	}
);

// TODO Add the option to specify time/date?
router.route('/tickets/:fromStation/:toStation').get(
	function(request, response) {
		httpRequest({
			uri: 'http://api.bart.gov/api/sched.aspx?cmd=depart&orig=' + request.param('fromStation') + '&dest=' + request.param('toStation') + '&time=9:00am' + '&b=0&a=1&key=' + bartApiKey,
			method: 'GET',
			timeout: 10000,
			followRedirect: true,
			maxRedirects: 10
		}, function(error, resp, body) {
			// TODO non-happy path
			var xmlStations = xmlParser.parseString(body, { trim: true, explicitArray: false }, function(err, res) {
				response.jsonp(res.root);
			});
		});
	}
);

// Prime the station list on startup and read periodically
loadStationList();
every('24h').do(function() {
	loadStationList();
});

app.use(cors());
app.use('/api', router);
app.listen(port);
console.log('BART API Server listening on port ' + port);
<|endoftext|>


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

// Constants
var PORT = 8888;

// App
var app = express();
app.get('/', function (req, res) {
  res.send('Hola pindonguita\n');
});

app.listen(PORT);
console.log('Running on http://localhost:' + PORT);
<commit_msg>updated server to support azure<commit_after>var express = require('express');

// Constants
var PORT = process.env.PORT || 8888;

// App
var app = express();
app.get('/', function (req, res) {
  res.send('Hola pindonguita\n');
});

app.listen(PORT);
console.log('Running on http://localhost:' + PORT);
<|endoftext|>


<commit_before>const express = require('express');
const pg = require('pg');
const config = require('./config');
const av_loader = require('./services/av_loader');
const constants = require('./constants');

const app = express();

var client = new pg.Client(process.env.DATABASE_URL || config.conString);
client.connect((err) => {
    if (err) console.log(err);
});

/*client.query('SELECT * FROM testdata', (err, res) => {
    console.log(err, res);
    console.log(res.rows[0].name);
    client.end();
}); */

function updateEntry(company, res) {
    //console.log(company);
    //console.log(res);
    client.query('UPDATE stockdata SET current_price=' +
        res.currentPrice.toFixed(2).toString() +
        ', mavg50=' + (res.mavg50 === undefined ? 0: res.mavg50).toString() +
        ', mavg100=' + (res.mavg100 === undefined ? 0: res.mavg100).toString() +
        ', mavg200=' + (res.mavg200 === undefined ? 0: res.mavg200).toString() +
        ', month3vol=' + res.threeMVol.toString() +
        ', day10vol=' + res.tenDayVol.toString() +
        ', percentchange5d=' + res.percentChange5D +
        ' WHERE symbol=\'' + company + '\'',
    (err, res) => {
        if (err) console.log(err);
    })
}

function updateFailureHandle() {
    console.log("An error while trying to access AlphaVantage");
}

/**
 * Updates database
 */
function updateDB() {
    console.log("Updating...");
    for (let i = 0; i < constants.companies.length; i++) {
        av_loader.avCall(constants.companies[i], updateEntry, updateFailureHandle); //TO BE CHANGED
    }
}

//Setup
app.get('/api/sanitycheck', function(req, res) {
    res.json({
        message: "Hello, API!"
    });
});

app.get('/api/stockdata', function(req, response){
    client.query('SELECT * FROM stockdata', (err, res) => {
        if (err) {
            console.log("An error occured while querying the db");
            response.json({error: "Database Error"});
        }
        else{
            response.json(res.rows);
        }
    });
});

updateDB();

setInterval(updateDB, 30000);

app.use(express.static(__dirname + '/dist'));
app.listen(process.env.PORT || 8080);
console.log("connected");<commit_msg>increased interval between updates<commit_after>const express = require('express');
const pg = require('pg');
const config = require('./config');
const av_loader = require('./services/av_loader');
const constants = require('./constants');

const app = express();

var client = new pg.Client(process.env.DATABASE_URL || config.conString);
client.connect((err) => {
    if (err) console.log(err);
});

/*client.query('SELECT * FROM testdata', (err, res) => {
    console.log(err, res);
    console.log(res.rows[0].name);
    client.end();
}); */

function updateEntry(company, res) {
    //console.log(company);
    //console.log(res);
    client.query('UPDATE stockdata SET current_price=' +
        res.currentPrice.toFixed(2).toString() +
        ', mavg50=' + (res.mavg50 === undefined ? 0: res.mavg50).toString() +
        ', mavg100=' + (res.mavg100 === undefined ? 0: res.mavg100).toString() +
        ', mavg200=' + (res.mavg200 === undefined ? 0: res.mavg200).toString() +
        ', month3vol=' + res.threeMVol.toString() +
        ', day10vol=' + res.tenDayVol.toString() +
        ', percentchange5d=' + res.percentChange5D +
        ' WHERE symbol=\'' + company + '\'',
    (err, res) => {
        if (err) console.log(err);
    })
}

function updateFailureHandle() {
    console.log("An error while trying to access AlphaVantage");
}

/**
 * Updates database
 */
function updateDB() {
    console.log("Updating...");
    for (let i = 0; i < constants.companies.length; i++) {
        av_loader.avCall(constants.companies[i], updateEntry, updateFailureHandle); //TO BE CHANGED
    }
}

//Setup
app.get('/api/sanitycheck', function(req, res) {
    res.json({
        message: "Hello, API!"
    });
});

app.get('/api/stockdata', function(req, response){
    client.query('SELECT * FROM stockdata', (err, res) => {
        if (err) {
            console.log("An error occured while querying the db");
            response.json({error: "Database Error"});
        }
        else{
            response.json(res.rows);
        }
    });
});

updateDB();

setInterval(updateDB, 60000);

app.use(express.static(__dirname + '/dist'));
app.listen(process.env.PORT || 8080);
console.log("connected");<|endoftext|>


<commit_before>var login = require("./facebook-chat-api");
var chrono = require('chrono-node');
var Firebase = require("firebase");

// Little binding to prevent heroku from complaining about port binding
var http = require('http');
http.createServer(function (req, res) {
}).listen(process.env.PORT || 5000);

if(!process.env.MARC_ZUCKERBOT_FIREBASE) return console.error("MARC_ZUCKERBOT_FIREBASE env variable isn't set!");
var db = new Firebase(process.env.MARC_ZUCKERBOT_FIREBASE);

function startBot(api, chats) {
  var currentUsername;
  var currentChat;
  var currentOtherUsernames;

  // Main method
  api.listen(function(message, closeConnection) {
    console.log("Received ->", message);
    var msg = read(message.body, message.sender_name.split(' ')[0], message.thread_id, message.participant_names);
    console.log("Sending ->", msg);

    if(msg.text && msg.text.length > 0) api.sendMessage(msg.text, message.thread_id);
    if(msg.sticker_id) api.sendMessage('', message.thread_id, msg.sticker_id);
  });

  // messages, username, chat id are Strings, otherUsernmaes is array of Strings
  var read = function(message, username, chatid, otherUsernames) {
    // Default chat object or existing one
    // And set the global object
    currentChat = chats[chatid] = chats[chatid] || {
      lists: {},
      scores: {},
      firstChat: true
    };
    if(!currentChat.lists) currentChat.lists = {};
    if(!currentChat.scores) currentChat.scores = {};

    if (currentChat.firstChat){
      currentChat.firstChat = false;
      api.sendMessage("Hey, type '/help' for some useful commands!", chatid);
    }

    currentUsername = username;
    currentOtherUsernames = otherUsernames;
    var textFunctions = [salute, weekendText, addScore, score, sexxiBatman, bees, ping, xkcdSearch, albert, arbitraryLists, slap, topScore, chatbot, sendStickerBigSmall, staticText, reminders];
    for (var i = 0; i < textFunctions.length; i++) {
        var res = textFunctions[i](message);
        if (res) {
          // Async saving to firebase
          db.set(chats);
          return res;
        }
    }
    return {};
  };

  var reminders = function(msg) {
    var myRegexp = /\/remind(.*)/i;
    var match = myRegexp.exec(msg);
    if(!match || match.length === 0) return;
    var rest = match[1].trim();
    console.log(rest);
    var ret = chrono.parse(rest);
    if(ret.length === 0) return;

    console.log(ret);
    return {text: "Reminder at: " + ret[0].start.date().toISOString().replace(/T/, ' ').replace(/\..+/, '') + " --> '" + rest.replace(ret[0].text, '')+'\''};
  };

  var staticText = function(msg) {
      var possibilities = [
          [[/(hey marc$|marc\?)/i],["Sup", "Hey :D", "hey", "Me?", "yes?"]],
          [[/(sup|wassup|what's up|how are you)\??$/i], ["I'm tired", "Not much, you?", "Meh...", "I'm great, how about you?", "What's up with you?", "Nothing much, you?"]],
          [[/(who made you|who's your creator|where do you come from)/i], ["I'm a long story... About 24h long.", "I'm not too sure", "I never really asked myself this question."]],
          [[/(\/sayit)/i], ["David's an idiot"]],
          [[/\/(help.*)/],["Try these commands:\n- /list help\n- hey marc\n- /ping\n- /slap [name]\n- /sayit\n- /xkcd keyword\n- name++\n- /score [name]\n- /topscore"]]
      ];
      for (var i = 0; i < possibilities.length; i++) {
          var possibleMatches = possibilities[i][0];
          for (var j = 0; j < possibleMatches.length; j++) {
              var match = possibleMatches[j].exec(msg);
              if(match && match.length > 0) {
                  return {text: randFrom(possibilities[i][1])};
              }
          }
      }
  };

  var sendStickerBigSmall = function(msg) {
      var possibilities = [
          [[/(small|big)/i], [767334526626290, 767334556626287, 767334506626292]]
      ];
      for (var i = 0; i < possibilities.length; i++) {
          var possibleMatches = possibilities[i][0];
          for (var j = 0; j < possibleMatches.length; j++) {
              var match = possibleMatches[j].exec(msg);
              if(match && match.length > 0) {
                  return {sticker_id: randFrom(possibilities[i][1])};
              }
          }
      }
  };

  var slap = function(msg) {
      var myRegexp = /^\/(slap\s*.*)/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;

      var arr = match[1].trim().toLowerCase();
      var list = arr.split(/\s+/);
      if(list.length === 1) return {text: currentOtherUsernames[~~(currentOtherUsernames.length * Math.random())] + " just got slapped."};

      var name = list[1];
      if(name === "me") return {text: currentUsername + " just go slapped." + (Math.random() > 0.5 ? " Hard.": "")};

      var exists = currentOtherUsernames.filter(function(v) {return v === name;}).length === 1;

      return {text: capitalize(name) + " just got slapped." + (Math.random() > 0.5 ? " Hard.": "")};
  };

  var weekendText = function(msg) {
      var myRegexp = /is it (weekend)\s?\?/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;
      var today = new Date();
      return {text: (today.getDay() === 0 || today.getDay() === 6 ? "YES" : "NO")};
  };

  var addScore = function(msg) {
    var myRegexp = /^(.+)\+\+/i;
    var match = myRegexp.exec(msg);
    if (!match || match.length < 1) return;
    var name = match[1].trim().toLowerCase();

    name = capitalize(name);
    if (name === currentUsername) {
      return {text: name + ", you can't upvote yourself -_- "};
    }
    if (contains(currentOtherUsernames, name)) {
      var score = (currentChat.scores[name] ? currentChat.scores[name] : 0) + 1;
      currentChat.scores[name] = score;
      return {text: name + "'s score is now " + score + "."};
    }

    return {text: "Who's " + name + "?"};
  };

  var salute = function(msg) {
      var myRegexp = /general\s+(\w+)/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;

      var general = match[1].trim();
      return {text: ("*salute* General " + general)};
  };

  var score = function(msg) {
      var myRegexp = /^\/score([\w .\-]*)$/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;
      var name = match[1].trim().toLowerCase();
      if (name.length < 1 || name === "me") name = currentUsername;

      name = capitalize(name);
      if (!contains(currentOtherUsernames, name)) return {text: "who?"};

      var pts = currentChat.scores[name] ? currentChat.scores[name] : 0;
      return {text: ("" + name + " has " + pts + " points")};
  };

  var albert = function(msg) {
      var myRegexp = /^\/albert$/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;
      var k =  "\n         ,---,_          ,\n          _>   `'-.  .--'/\n     .--'` ._      `/   <_\n      >,-' ._'.. ..__ . ' '-.\n   .-'   .'`         `'.     '.\n    >   / >`-.     .-'< \\ , '._\\\n   /    ; '-._>   <_.-' ;  '._>\n   `>  ,/  /___\\ /___\\  \\_  /\n   `.-|(|  \\o_/  \\o_/   |)|`\n       \\;        \\      ;/\n         \\  .-,   )-.  /\n          /`  .'-'.  `\\\n         ;_.-`.___.'-.;\n";
  return {text: k};
  };

  var bees = function(msg) {
      if (msg.indexOf("bees") > -1) {
          return {text: "http://cdn.gifstache.com/2012/7/19/gifstache.com_893_1342731571.gif"};
      }
  };

  var sexxiBatman = function(msg) {
      if (msg.match(/[Ww]anna make some trouble[\s\t]*/)) {
          return {text: "http://99gifs.com/-img/514e8830afa96f09940128f8.gif"};
      }
  };

  var ping = function(msg) {
      var myRegexp = /^\/ping$/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;
      return {text: "pong"};
  };

  var xkcdSearch = function(msg) {
      var myRegexp = /^\/xkcd\s+(.+)/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;
      var search = match[1].trim().toLowerCase().replace(/ /g, "+");
      var searchUrl = "http://derp.co.uk/xkcd/page?q=" + search + "&search=Search";
      return {text: "Find relevant xkcds here: " + searchUrl};
  };

  var giphySearch = function(msg) {
      var data = "";
      if(msg.indexOf("giphy") > -1) {
          var strippedString = msg.replace(/^\s+|\s+$/g, '');
          strippedString = strippedString.replace("giphy", '');

          var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
          var request = new XMLHttpRequest();
          request.open('GET', 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag='+strippedString, false);

          request.onload = function() {
              if (request.status >= 200 && request.status < 400){
                  data = JSON.parse(request.responseText).data.image_url;
                  console.log(data);
                  return {text: data};
              } else {
                  return {text: "No gif for this search result."};
              }
          };

          request.onerror = function() {
              console.log('Connection error');
          };

          request.send(null);
          console.log("request sent");
      }
  };

  var arbitraryLists = function (msg) {
    var myRegexp = /^\/(list\s*.*)/i;
    var match = myRegexp.exec(msg);
    if (!match || match.length < 1) return;

    var list = match[1].trim().toLowerCase();
    var arr = list.split(/\s+/);
    if(arr.length === 1) return {text: (Object.keys(currentChat.lists).length > 0 ? "Existing Lists: \n" + Object.keys(currentChat.lists).map(function(v, i) {
      return (i + 1) + " - " + v;
    }).join("\n") : "No existing list.")};

    var keyword = arr[1];
    var listName = arr.length > 2 ? arr[2] : "";
    if(keyword === 'new') {
      if(listName.length > 0) {
        currentChat.lists[listName] = [];
        return {text: "List '" + listName + "' created."};
      }
    } else if (keyword === 'delete') {
      if(arr.length > 3) {
        var num = parseInt(arr[3]);
        if(num - 1 >= currentChat.lists[listName].length || num - 1 < 0) {
          return {text: "Item " + num + " in list '" + listName + "' doesn't exist."};
        }
        currentChat.lists[listName].splice(num - 1, 1);
        return {text: "Item " + num + " in list '" + listName + "' deleted."};
      }
      if(listName.length > 0) {
        delete currentChat.lists[listName];
        return {text: "List '" + listName + "' deleted."};
      }
    } else if (keyword === 'add') {
      if(listName.length > 0 && arr.length > 3) {
        if (!currentChat.lists[listName]) {
          return {text: "No list of name '"+listName+"' exists."};
        }
        currentChat.lists[listName].push(arr.slice(3).join(' '));
        return {text: "Added '" + arr.slice(3).join(' ') + "' to " + listName + "."};
      }
    } else if (currentChat.lists[keyword]) {
      return {text: keyword + ": \n" + currentChat.lists[keyword].map(function(v, i) {return (i + 1) + " - " + v;}).join("\n")};
    }

    return {text: "Usage:\n /list \n /list list-name\n /list new list-name \n /list delete list-name \n /list add list-name new-element"};
  };

  var topScore = function(msg) {
    var myRegexp = /^\/(topscores?)$/i;
    var match = myRegexp.exec(msg);
    if (!match || match.length < 1) return;
    var max = -1;
    var maxName = "";
    for (var i = 0; i < currentOtherUsernames.length; i++) {
      var score = currentChat.scores[currentOtherUsernames[i]] ? currentChat.scores[currentOtherUsernames[i]] : 0;
      if (score > max) {
        max = score;
        maxName = currentOtherUsernames[i];
      }
    }
    return {text: "Top Score: " + maxName+ ", with "+max+" points."};
  };

  var chatbot = function(msg) {
    var myRegexp = /((chat)? ?bots?)/i;
    var match = myRegexp.exec(msg);
    if (!match || match.length < 1) return;
    var items = ["Are you talking about me?", "I am a chat bot.", "Pick me, pick me!"];
    return {text: items[Math.floor(Math.random()*items.length)]};
  };

  function capitalize(name) {
    return name.charAt(0).toUpperCase() + name.slice(1);
  }

  function randFrom(arr) {
    return arr[~~(arr.length * Math.random())];
  }

  function replaceAll(find, replace, str) {
    return str.replace(new RegExp(find, 'g'), replace);
  }

  function contains(array, obj) {
    for (var i = array.length - 1; i >= 0; i--) {
      if (array[i] === obj) return true;
    }
    return false;
  }
}

// Main function
db.once('value', function(snapshot) {
  var chats = snapshot.val() || {};
  login(function(api) {
    startBot(api, chats);
  });
});
<commit_msg>swapped bool<commit_after>var login = require("./facebook-chat-api");
var chrono = require('chrono-node');
var Firebase = require("firebase");

// Little binding to prevent heroku from complaining about port binding
var http = require('http');
http.createServer(function (req, res) {
}).listen(process.env.PORT || 5000);

if(!process.env.MARC_ZUCKERBOT_FIREBASE) return console.error("MARC_ZUCKERBOT_FIREBASE env variable isn't set!");
var db = new Firebase(process.env.MARC_ZUCKERBOT_FIREBASE);

function startBot(api, chats) {
  var currentUsername;
  var currentChat;
  var currentOtherUsernames;

  // Main method
  api.listen(function(message, closeConnection) {
    console.log("Received ->", message);
    var msg = read(message.body, message.sender_name.split(' ')[0], message.thread_id, message.participant_names);
    console.log("Sending ->", msg);

    if(msg.text && msg.text.length > 0) api.sendMessage(msg.text, message.thread_id);
    if(msg.sticker_id) api.sendMessage('', message.thread_id, msg.sticker_id);
  });

  // messages, username, chat id are Strings, otherUsernmaes is array of Strings
  var read = function(message, username, chatid, otherUsernames) {
    // Default chat object or existing one
    // And set the global object
    currentChat = chats[chatid] = chats[chatid] || {
      lists: {},
      scores: {},
      existingChat: false
    };
    if(!currentChat.lists) currentChat.lists = {};
    if(!currentChat.scores) currentChat.scores = {};

    if (!currentChat.existingChat){
      currentChat.existingChat = true;
      api.sendMessage("Hey, type '/help' for some useful commands!", chatid);
    }

    currentUsername = username;
    currentOtherUsernames = otherUsernames;
    var textFunctions = [salute, weekendText, addScore, score, sexxiBatman, bees, ping, xkcdSearch, albert, arbitraryLists, slap, topScore, chatbot, sendStickerBigSmall, staticText, reminders];
    for (var i = 0; i < textFunctions.length; i++) {
        var res = textFunctions[i](message);
        if (res) {
          // Async saving to firebase
          db.set(chats);
          return res;
        }
    }
    return {};
  };

  var reminders = function(msg) {
    var myRegexp = /\/remind(.*)/i;
    var match = myRegexp.exec(msg);
    if(!match || match.length === 0) return;
    var rest = match[1].trim();
    console.log(rest);
    var ret = chrono.parse(rest);
    if(ret.length === 0) return;

    console.log(ret);
    return {text: "Reminder at: " + ret[0].start.date().toISOString().replace(/T/, ' ').replace(/\..+/, '') + " --> '" + rest.replace(ret[0].text, '')+'\''};
  };

  var staticText = function(msg) {
      var possibilities = [
          [[/(hey marc$|marc\?)/i],["Sup", "Hey :D", "hey", "Me?", "yes?"]],
          [[/(sup|wassup|what's up|how are you)\??$/i], ["I'm tired", "Not much, you?", "Meh...", "I'm great, how about you?", "What's up with you?", "Nothing much, you?"]],
          [[/(who made you|who's your creator|where do you come from)/i], ["I'm a long story... About 24h long.", "I'm not too sure", "I never really asked myself this question."]],
          [[/(\/sayit)/i], ["David's an idiot"]],
          [[/\/(help.*)/],["Try these commands:\n- /list help\n- hey marc\n- /ping\n- /slap [name]\n- /sayit\n- /xkcd keyword\n- name++\n- /score [name]\n- /topscore"]]
      ];
      for (var i = 0; i < possibilities.length; i++) {
          var possibleMatches = possibilities[i][0];
          for (var j = 0; j < possibleMatches.length; j++) {
              var match = possibleMatches[j].exec(msg);
              if(match && match.length > 0) {
                  return {text: randFrom(possibilities[i][1])};
              }
          }
      }
  };

  var sendStickerBigSmall = function(msg) {
      var possibilities = [
          [[/(small|big)/i], [767334526626290, 767334556626287, 767334506626292]]
      ];
      for (var i = 0; i < possibilities.length; i++) {
          var possibleMatches = possibilities[i][0];
          for (var j = 0; j < possibleMatches.length; j++) {
              var match = possibleMatches[j].exec(msg);
              if(match && match.length > 0) {
                  return {sticker_id: randFrom(possibilities[i][1])};
              }
          }
      }
  };

  var slap = function(msg) {
      var myRegexp = /^\/(slap\s*.*)/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;

      var arr = match[1].trim().toLowerCase();
      var list = arr.split(/\s+/);
      if(list.length === 1) return {text: currentOtherUsernames[~~(currentOtherUsernames.length * Math.random())] + " just got slapped."};

      var name = list[1];
      if(name === "me") return {text: currentUsername + " just go slapped." + (Math.random() > 0.5 ? " Hard.": "")};

      var exists = currentOtherUsernames.filter(function(v) {return v === name;}).length === 1;

      return {text: capitalize(name) + " just got slapped." + (Math.random() > 0.5 ? " Hard.": "")};
  };

  var weekendText = function(msg) {
      var myRegexp = /is it (weekend)\s?\?/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;
      var today = new Date();
      return {text: (today.getDay() === 0 || today.getDay() === 6 ? "YES" : "NO")};
  };

  var addScore = function(msg) {
    var myRegexp = /^(.+)\+\+/i;
    var match = myRegexp.exec(msg);
    if (!match || match.length < 1) return;
    var name = match[1].trim().toLowerCase();

    name = capitalize(name);
    if (name === currentUsername) {
      return {text: name + ", you can't upvote yourself -_- "};
    }
    if (contains(currentOtherUsernames, name)) {
      var score = (currentChat.scores[name] ? currentChat.scores[name] : 0) + 1;
      currentChat.scores[name] = score;
      return {text: name + "'s score is now " + score + "."};
    }

    return {text: "Who's " + name + "?"};
  };

  var salute = function(msg) {
      var myRegexp = /general\s+(\w+)/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;

      var general = match[1].trim();
      return {text: ("*salute* General " + general)};
  };

  var score = function(msg) {
      var myRegexp = /^\/score([\w .\-]*)$/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;
      var name = match[1].trim().toLowerCase();
      if (name.length < 1 || name === "me") name = currentUsername;

      name = capitalize(name);
      if (!contains(currentOtherUsernames, name)) return {text: "who?"};

      var pts = currentChat.scores[name] ? currentChat.scores[name] : 0;
      return {text: ("" + name + " has " + pts + " points")};
  };

  var albert = function(msg) {
      var myRegexp = /^\/albert$/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;
      var k =  "\n         ,---,_          ,\n          _>   `'-.  .--'/\n     .--'` ._      `/   <_\n      >,-' ._'.. ..__ . ' '-.\n   .-'   .'`         `'.     '.\n    >   / >`-.     .-'< \\ , '._\\\n   /    ; '-._>   <_.-' ;  '._>\n   `>  ,/  /___\\ /___\\  \\_  /\n   `.-|(|  \\o_/  \\o_/   |)|`\n       \\;        \\      ;/\n         \\  .-,   )-.  /\n          /`  .'-'.  `\\\n         ;_.-`.___.'-.;\n";
  return {text: k};
  };

  var bees = function(msg) {
      if (msg.indexOf("bees") > -1) {
          return {text: "http://cdn.gifstache.com/2012/7/19/gifstache.com_893_1342731571.gif"};
      }
  };

  var sexxiBatman = function(msg) {
      if (msg.match(/[Ww]anna make some trouble[\s\t]*/)) {
          return {text: "http://99gifs.com/-img/514e8830afa96f09940128f8.gif"};
      }
  };

  var ping = function(msg) {
      var myRegexp = /^\/ping$/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;
      return {text: "pong"};
  };

  var xkcdSearch = function(msg) {
      var myRegexp = /^\/xkcd\s+(.+)/i;
      var match = myRegexp.exec(msg);
      if (!match || match.length < 1) return;
      var search = match[1].trim().toLowerCase().replace(/ /g, "+");
      var searchUrl = "http://derp.co.uk/xkcd/page?q=" + search + "&search=Search";
      return {text: "Find relevant xkcds here: " + searchUrl};
  };

  var giphySearch = function(msg) {
      var data = "";
      if(msg.indexOf("giphy") > -1) {
          var strippedString = msg.replace(/^\s+|\s+$/g, '');
          strippedString = strippedString.replace("giphy", '');

          var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
          var request = new XMLHttpRequest();
          request.open('GET', 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag='+strippedString, false);

          request.onload = function() {
              if (request.status >= 200 && request.status < 400){
                  data = JSON.parse(request.responseText).data.image_url;
                  console.log(data);
                  return {text: data};
              } else {
                  return {text: "No gif for this search result."};
              }
          };

          request.onerror = function() {
              console.log('Connection error');
          };

          request.send(null);
          console.log("request sent");
      }
  };

  var arbitraryLists = function (msg) {
    var myRegexp = /^\/(list\s*.*)/i;
    var match = myRegexp.exec(msg);
    if (!match || match.length < 1) return;

    var list = match[1].trim().toLowerCase();
    var arr = list.split(/\s+/);
    if(arr.length === 1) return {text: (Object.keys(currentChat.lists).length > 0 ? "Existing Lists: \n" + Object.keys(currentChat.lists).map(function(v, i) {
      return (i + 1) + " - " + v;
    }).join("\n") : "No existing list.")};

    var keyword = arr[1];
    var listName = arr.length > 2 ? arr[2] : "";
    if(keyword === 'new') {
      if(listName.length > 0) {
        currentChat.lists[listName] = [];
        return {text: "List '" + listName + "' created."};
      }
    } else if (keyword === 'delete') {
      if(arr.length > 3) {
        var num = parseInt(arr[3]);
        if(num - 1 >= currentChat.lists[listName].length || num - 1 < 0) {
          return {text: "Item " + num + " in list '" + listName + "' doesn't exist."};
        }
        currentChat.lists[listName].splice(num - 1, 1);
        return {text: "Item " + num + " in list '" + listName + "' deleted."};
      }
      if(listName.length > 0) {
        delete currentChat.lists[listName];
        return {text: "List '" + listName + "' deleted."};
      }
    } else if (keyword === 'add') {
      if(listName.length > 0 && arr.length > 3) {
        if (!currentChat.lists[listName]) {
          return {text: "No list of name '"+listName+"' exists."};
        }
        currentChat.lists[listName].push(arr.slice(3).join(' '));
        return {text: "Added '" + arr.slice(3).join(' ') + "' to " + listName + "."};
      }
    } else if (currentChat.lists[keyword]) {
      return {text: keyword + ": \n" + currentChat.lists[keyword].map(function(v, i) {return (i + 1) + " - " + v;}).join("\n")};
    }

    return {text: "Usage:\n /list \n /list list-name\n /list new list-name \n /list delete list-name \n /list add list-name new-element"};
  };

  var topScore = function(msg) {
    var myRegexp = /^\/(topscores?)$/i;
    var match = myRegexp.exec(msg);
    if (!match || match.length < 1) return;
    var max = -1;
    var maxName = "";
    for (var i = 0; i < currentOtherUsernames.length; i++) {
      var score = currentChat.scores[currentOtherUsernames[i]] ? currentChat.scores[currentOtherUsernames[i]] : 0;
      if (score > max) {
        max = score;
        maxName = currentOtherUsernames[i];
      }
    }
    return {text: "Top Score: " + maxName+ ", with "+max+" points."};
  };

  var chatbot = function(msg) {
    var myRegexp = /((chat)? ?bots?)/i;
    var match = myRegexp.exec(msg);
    if (!match || match.length < 1) return;
    var items = ["Are you talking about me?", "I am a chat bot.", "Pick me, pick me!"];
    return {text: items[Math.floor(Math.random()*items.length)]};
  };

  function capitalize(name) {
    return name.charAt(0).toUpperCase() + name.slice(1);
  }

  function randFrom(arr) {
    return arr[~~(arr.length * Math.random())];
  }

  function replaceAll(find, replace, str) {
    return str.replace(new RegExp(find, 'g'), replace);
  }

  function contains(array, obj) {
    for (var i = array.length - 1; i >= 0; i--) {
      if (array[i] === obj) return true;
    }
    return false;
  }
}

// Main function
db.once('value', function(snapshot) {
  var chats = snapshot.val() || {};
  login(function(api) {
    startBot(api, chats);
  });
});
<|endoftext|>


<commit_before>HOST = null; // localhost
PORT = 8000;

var fu = require("fu");

var MESSAGE_BACKLOG = 200;
var SESSION_TIMEOUT = 60 * 1000;

var channel = new function () {
  var messages = [];
  var callbacks = [];

  this.appendMessage = function (nick, type, text) {
    var m = { nick: nick
            , type: type // "msg", "join", "part"
            , text: text
            , timestamp: (new Date()).getTime()
            };

    messages.push( m );

    while (callbacks.length > 0) {
      callbacks.shift().callback([m]);
    }

    while (messages.length > MESSAGE_BACKLOG)
      messages.shift();
  };

  this.query = function (since, callback) {
    var matching = [];
    for (var i = 0; i < messages.length; i++) {
      var message = messages[i];
      if (message.timestamp > since)
        matching.push(message)
    }

    if (matching.length != 0) {
      callback(matching);
    } else {
      callbacks.push({ timestamp: new Date(), callback: callback });
    }
  };

  // clear old callbacks
  // they can hang around for at most 30 seconds.
  setInterval(function () {
    var now = new Date();
    while (callbacks.length > 0 && now - callbacks[0].timestamp > 30*1000) {
      callbacks.shift().callback([]);
    }
  }, 1000);
};

var sessions = {};

function createSession (nick) {
  if (nick.length > 50) return null;
  if (/[^\w_\-^!]/.exec(nick)) return null;

  for (var i in sessions) {
    var session = sessions[i];
    if (session && session.nick === nick) return null;
  }

  var session = {
    nick: nick,

    id: Math.floor(Math.random()*99999999999).toString(),

    timestamp: new Date(),

    poke: function () {
      session.timestamp = new Date();
    },

    destroy: function () {
      channel.appendMessage(session.nick, "part");
      delete sessions[session.id];
    }
  };

  sessions[session.id] = session;
  return session;
}

// interval to kill off old sessions
setInterval(function () {
  var now = new Date();
  for (var id in sessions) {
    if (!sessions.hasOwnProperty(id)) continue;
    var session = sessions[id];

    if (now - session.timestamp > SESSION_TIMEOUT) {
      session.destroy();
    }
  }
}, 1000);

function onLoad () {
  fu.listen(PORT, HOST);

  fu.get("/", fu.staticHandler("index.html"));
  fu.get("/style.css", fu.staticHandler("style.css"));
  fu.get("/client.js", fu.staticHandler("client.js"));
  fu.get("/jquery-1.2.6.min.js", fu.staticHandler("jquery-1.2.6.min.js"));

  fu.get("/who", function (req, res) {
    var nicks = [];
    for (var id in sessions) {
      if (!sessions.hasOwnProperty(id)) continue;
      var session = sessions[id];
      nicks.push(session.nick);
    }
    res.simpleJSON(200, { nicks: nicks });
  });

  fu.get("/join", function (req, res) {
    var nick = req.uri.params["nick"];
    if (nick == null || nick.length == 0) {
      res.simpleJSON(400, {error: "Bad nick."});
      return;
    }
    var session = createSession(nick);
    if (session == null) {
      res.simpleJSON(400, {error: "Nick in use"});
      return;
    }
    channel.appendMessage(session.nick, "join");
    res.simpleJSON(200, { id: session.id, nick: session.nick});
  });

  fu.get("/part", function (req, res) {
    var id = req.uri.params.id;
    var session;
    if (id && sessions[id]) {
      session = sessions[id];
      session.destroy();
    }
    res.simpleJSON(200, { });
  });

  fu.get("/recv", function (req, res) {
    if (!req.uri.params.since) {
      res.simpleJSON(400, { error: "Must supply since parameter" });
      return;
    }
    var id = req.uri.params.id;
    var session;
    if (id && sessions[id]) {
      session = sessions[id];
      session.poke();
    }

    var since = parseInt(req.uri.params.since, 10);

    channel.query(since, function (messages) {
      if (session) session.poke();
      res.simpleJSON(200, { messages: messages });
    });
  });

  fu.get("/send", function (req, res) {
    var id = req.uri.params.id;
    var text = req.uri.params.text;

    var session = sessions[id];
    if (!session || !text) {
      res.simpleJSON(400, { error: "No such session id" });
      return;
    }

    session.poke();

    channel.appendMessage(session.nick, "msg", text);
    res.simpleJSON(200, {});
  });
}
<commit_msg>update for node v0.0.3<commit_after>HOST = null; // localhost
PORT = 7000;

var fu = require("fu.js");

var MESSAGE_BACKLOG = 200;
var SESSION_TIMEOUT = 60 * 1000;

var channel = new function () {
  var messages = [];
  var callbacks = [];

  this.appendMessage = function (nick, type, text) {
    var m = { nick: nick
            , type: type // "msg", "join", "part"
            , text: text
            , timestamp: (new Date()).getTime()
            };

    messages.push( m );

    while (callbacks.length > 0) {
      callbacks.shift().callback([m]);
    }

    while (messages.length > MESSAGE_BACKLOG)
      messages.shift();
  };

  this.query = function (since, callback) {
    var matching = [];
    for (var i = 0; i < messages.length; i++) {
      var message = messages[i];
      if (message.timestamp > since)
        matching.push(message)
    }

    if (matching.length != 0) {
      callback(matching);
    } else {
      callbacks.push({ timestamp: new Date(), callback: callback });
    }
  };

  // clear old callbacks
  // they can hang around for at most 30 seconds.
  setInterval(function () {
    var now = new Date();
    while (callbacks.length > 0 && now - callbacks[0].timestamp > 30*1000) {
      callbacks.shift().callback([]);
    }
  }, 1000);
};

var sessions = {};

function createSession (nick) {
  if (nick.length > 50) return null;
  if (/[^\w_\-^!]/.exec(nick)) return null;

  for (var i in sessions) {
    var session = sessions[i];
    if (session && session.nick === nick) return null;
  }

  var session = {
    nick: nick,

    id: Math.floor(Math.random()*99999999999).toString(),

    timestamp: new Date(),

    poke: function () {
      session.timestamp = new Date();
    },

    destroy: function () {
      channel.appendMessage(session.nick, "part");
      delete sessions[session.id];
    }
  };

  sessions[session.id] = session;
  return session;
}

// interval to kill off old sessions
setInterval(function () {
  var now = new Date();
  for (var id in sessions) {
    if (!sessions.hasOwnProperty(id)) continue;
    var session = sessions[id];

    if (now - session.timestamp > SESSION_TIMEOUT) {
      session.destroy();
    }
  }
}, 1000);

function onLoad () {
  fu.listen(PORT, HOST);

  fu.get("/", fu.staticHandler("index.html"));
  fu.get("/style.css", fu.staticHandler("style.css"));
  fu.get("/client.js", fu.staticHandler("client.js"));
  fu.get("/jquery-1.2.6.min.js", fu.staticHandler("jquery-1.2.6.min.js"));

  fu.get("/who", function (req, res) {
    var nicks = [];
    for (var id in sessions) {
      if (!sessions.hasOwnProperty(id)) continue;
      var session = sessions[id];
      nicks.push(session.nick);
    }
    res.simpleJSON(200, { nicks: nicks });
  });

  fu.get("/join", function (req, res) {
    var nick = req.uri.params["nick"];
    if (nick == null || nick.length == 0) {
      res.simpleJSON(400, {error: "Bad nick."});
      return;
    }
    var session = createSession(nick);
    if (session == null) {
      res.simpleJSON(400, {error: "Nick in use"});
      return;
    }
    channel.appendMessage(session.nick, "join");
    res.simpleJSON(200, { id: session.id, nick: session.nick});
  });

  fu.get("/part", function (req, res) {
    var id = req.uri.params.id;
    var session;
    if (id && sessions[id]) {
      session = sessions[id];
      session.destroy();
    }
    res.simpleJSON(200, { });
  });

  fu.get("/recv", function (req, res) {
    if (!req.uri.params.since) {
      res.simpleJSON(400, { error: "Must supply since parameter" });
      return;
    }
    var id = req.uri.params.id;
    var session;
    if (id && sessions[id]) {
      session = sessions[id];
      session.poke();
    }

    var since = parseInt(req.uri.params.since, 10);

    channel.query(since, function (messages) {
      if (session) session.poke();
      res.simpleJSON(200, { messages: messages });
    });
  });

  fu.get("/send", function (req, res) {
    var id = req.uri.params.id;
    var text = req.uri.params.text;

    var session = sessions[id];
    if (!session || !text) {
      res.simpleJSON(400, { error: "No such session id" });
      return;
    }

    session.poke();

    channel.appendMessage(session.nick, "msg", text);
    res.simpleJSON(200, {});
  });
}
<|endoftext|>


<commit_before>const express = require('express');
const path = require('path');
const fs = require('fs');
const formidable = require('formidable');
const helper = require('sendgrid').mail;
require('dotenv').config();
const sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
const fetch = require('node-fetch');

const app = express();
const PORT = process.env.PORT || 9000;
// const CLIENT_PORT = process.env.PORT || 3000;
const PROTOCOL = process.env.PROTOCOL || 'http';
const HOSTNAME = process.env.HOST || 'localhost';
const UPLOAD_DIR = path.join(__dirname, 'uploads/');
const CORS = process.env.NODE_ENV === 'production' ? `${PROTOCOL}://${HOSTNAME}` : `*`;
const ENABLE_SEND_EMAILS = process.env.NODE_ENV === 'production' || process.env.ENABLE_SEND_EMAILS === 'true';

if (ENABLE_SEND_EMAILS) {
  console.info('Sending emails is enabled');
} else {
  console.info('Sending emails is disabled');
}

// This converts {a:1, b:2} into 'a=1&b=2'
const queryParams = obj =>
  Object.keys(obj)
    .map(key => [key, obj[key]]) // There is no Object.entries() in node 6
    .map(
      ([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`
    )
    .join('&');

const wrikeMkFolder = name =>
  fetch(process.env.WRIKE_URL, {
    body: queryParams({
      title: name,
      description: 'folder description',
    }),
    method: 'post',
    headers: {
      Authorization: `bearer ${process.env.WRIKE_TOKEN}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  }).then(res => res.text());

const toEmail = new helper.Email('paulius.rimg1990@gmail.com');

const makeSgRequest = body =>
  sg.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: body.toJSON(),
  });

if (!fs.existsSync(UPLOAD_DIR)) {
  console.warn('==========================');
  console.warn('Creating uploads folder...');
  console.warn('==========================');
  fs.mkdirSync(UPLOAD_DIR);
}
console.info('======================================');
console.info(`Uploads will be saved in ${UPLOAD_DIR}`);
console.info('======================================');

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

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

app.post('/uploads', (req, res) => {
  const form = new formidable.IncomingForm();

  // In any case send the cors headers (even on error)
  res.header('Access-Control-Allow-Origin', CORS);
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );

  form.parse(req);

  // The events we subscribe to in the form occur in the following order
  // field - multiple times
  // fileBegin then file - once per file
  // error - only if there was a parsing error
  // end - when all other events have been handled and the files have
  //       finished being written to the disk, this event happens even
  //       if there was an error

  form.on('fileBegin', (name, file) => {
    file.path = path.join(UPLOAD_DIR, file.name);
  });

  form.on('file', (name, file) => {
    console.log(`Uploaded ${file.name}`);
  });

  const fields = {};
  form.on('field', (name, value) => {
    fields[name] = value;
  });

  // Handle a possible error while parsing the request
  // We need a variable in this scope to hold whether there was an error
  // because we need to know that in a different callback
  let error = false;
  form.on('error', (err) => {
    error = true;
    console.log('Error while parsing request to /uploads: ', err);
    res
      .status(400) // Bad request
      .json({
        success: false,
        status: 'Error parsing the request',
      });
  });

  form.on('end', () => {
    // The end event is fired even if an error occurs, so we
    // need to prevent from sending a second response, otherwise the
    // server crashes
    if (error) return;
    console.log('Received fields:\n', JSON.stringify(fields, null, 2));

    // TODO: Validate fields

    // Here is a good place to send the emails since we have the fields
    // We don't want to actually send emails during testing since it
    // would send a test email on every single commit
    if (ENABLE_SEND_EMAILS) {
      const fromEmail = new helper.Email('test@example.com');
      const subject = 'Sending with SendGrid is Fun';
      const content = new helper.Content(
        'text/plain',
        'and easy to do anywhere, even with Node.js'
      );
      const mail = new helper.Mail(fromEmail, subject, toEmail, content);
      const request = makeSgRequest(mail);
      console.log('Sending email...');
      sg.API(request, (err, res) => {
        if (error) {
          console.log('Error response received');
        }
        console.log(res.statusCode);
        console.log(res.body);
        console.log(res.headers);
      });
    }

    wrikeMkFolder('test')
      .then(status => console.log(status))
      .catch(console.log);

    // Send the success response
    res
      .status(200)
      .json({ success: true, status: 'Form successfully submitted' });
  });
});

app.listen(PORT, _ =>
  console.info('============================'),
console.info(`Server listening on PORT ${PORT}...`),
console.info('============================'));
<commit_msg># Create wrike project instead of folder on form submission<commit_after>const express = require('express');
const path = require('path');
const fs = require('fs');
const formidable = require('formidable');
const helper = require('sendgrid').mail;
require('dotenv').config();
const sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
const fetch = require('node-fetch');

const app = express();
const PORT = process.env.PORT || 9000;
// const CLIENT_PORT = process.env.PORT || 3000;
const PROTOCOL = process.env.PROTOCOL || 'http';
const HOSTNAME = process.env.HOST || 'localhost';
const UPLOAD_DIR = path.join(__dirname, 'uploads/');
const CORS = process.env.NODE_ENV === 'production' ? `${PROTOCOL}://${HOSTNAME}` : `*`;
const ENABLE_SEND_EMAILS = process.env.NODE_ENV === 'production' || process.env.ENABLE_SEND_EMAILS === 'true';

if (ENABLE_SEND_EMAILS) {
  console.info('Sending emails is enabled');
} else {
  console.info('Sending emails is disabled');
}

// This converts {a:1, b:2} into 'a=1&b=2'
const queryParams = obj =>
  Object.keys(obj)
    .map(key => [key, obj[key]]) // There is no Object.entries() in node 6
    .map(
      ([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`
    )
    .join('&');

const wrikeMkFolder = name =>
  fetch(process.env.WRIKE_URL, {
    body: queryParams({
      title: name,
      description: 'folder description',
      shareds: process.env.WRIKE_SHARE_ID,
      project: process.env.WRIKE_OWNER_ID,
    }),
    method: 'post',
    headers: {
      Authorization: `bearer ${process.env.WRIKE_TOKEN}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  }).then(res => res.text());

const toEmail = new helper.Email('paulius.rimg1990@gmail.com');

const makeSgRequest = body =>
  sg.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: body.toJSON(),
  });

if (!fs.existsSync(UPLOAD_DIR)) {
  console.warn('==========================');
  console.warn('Creating uploads folder...');
  console.warn('==========================');
  fs.mkdirSync(UPLOAD_DIR);
}
console.info('======================================');
console.info(`Uploads will be saved in ${UPLOAD_DIR}`);
console.info('======================================');

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

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

app.post('/uploads', (req, res) => {
  const form = new formidable.IncomingForm();

  // In any case send the cors headers (even on error)
  res.header('Access-Control-Allow-Origin', CORS);
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );

  form.parse(req);

  // The events we subscribe to in the form occur in the following order
  // field - multiple times
  // fileBegin then file - once per file
  // error - only if there was a parsing error
  // end - when all other events have been handled and the files have
  //       finished being written to the disk, this event happens even
  //       if there was an error

  form.on('fileBegin', (name, file) => {
    file.path = path.join(UPLOAD_DIR, file.name);
  });

  form.on('file', (name, file) => {
    console.log(`Uploaded ${file.name}`);
  });

  const fields = {};
  form.on('field', (name, value) => {
    fields[name] = value;
  });

  // Handle a possible error while parsing the request
  // We need a variable in this scope to hold whether there was an error
  // because we need to know that in a different callback
  let error = false;
  form.on('error', (err) => {
    error = true;
    console.log('Error while parsing request to /uploads: ', err);
    res
      .status(400) // Bad request
      .json({
        success: false,
        status: 'Error parsing the request',
      });
  });

  form.on('end', () => {
    // The end event is fired even if an error occurs, so we
    // need to prevent from sending a second response, otherwise the
    // server crashes
    if (error) return;
    console.log('Received fields:\n', JSON.stringify(fields, null, 2));

    // TODO: Validate fields

    // Here is a good place to send the emails since we have the fields
    // We don't want to actually send emails during testing since it
    // would send a test email on every single commit
    if (ENABLE_SEND_EMAILS) {
      const fromEmail = new helper.Email('test@example.com');
      const subject = 'Sending with SendGrid is Fun';
      const content = new helper.Content(
        'text/plain',
        'and easy to do anywhere, even with Node.js'
      );
      const mail = new helper.Mail(fromEmail, subject, toEmail, content);
      const request = makeSgRequest(mail);
      console.log('Sending email...');
      sg.API(request, (err, res) => {
        if (error) {
          console.log('Error response received');
        }
        console.log(res.statusCode);
        console.log(res.body);
        console.log(res.headers);
      });
    }

    wrikeMkFolder('test')
      .then(status => console.log(status))
      .catch(console.log);

    // Send the success response
    res
      .status(200)
      .json({ success: true, status: 'Form successfully submitted' });
  });
});

app.listen(PORT, _ =>
  console.info('============================'),
console.info(`Server listening on PORT ${PORT}...`),
console.info('============================'));
<|endoftext|>


<commit_before>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');

var publicDirectory = "css";

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";
            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express.createServer();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }

        ['css', 'img', 'js', 'plugin', 'lib'].forEach(function (dir){
            self.app.use('/src/'+dir, express.static(__dirname+'/src/'+dir));
        });
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<commit_msg>updated server.js<commit_after>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');

var publicDirectory = "css";

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./src/index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";
            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express.createServer();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }

        ['css', 'img', 'js', 'plugin', 'lib'].forEach(function (dir){
            self.app.use('/src/'+dir, express.static(__dirname+'/src/'+dir));
        });
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<|endoftext|>