<commit_before>
if (!process.env.NODE_ENV)
  var dotenv = require('dotenv').load();

var twilio = require('twilio');
var Keen = require('keen.io');
var _ = require('lodash');
var express = require('express');
var logfmt = require('logfmt');
var moment = require('moment');
var Promise = require('bluebird');
var db = require('./db');
var app = express();

var keenClient = Keen.configure({
  projectId: process.env.KEEN_PROJECT_ID,
  writeKey: process.env.KEEN_WRITE_KEY
});

// Express Middleware
app.use(logfmt.requestLogger());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser(process.env.COOKIE_SECRET));
app.use(express.cookieSession());

// Allows CORS
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});

// Enable CORS support for IE8.
app.get('/proxy.html', function(req, res) {
  res.send('<!DOCTYPE HTML>\n' + '<script src="http://jpillora.com/xdomain/dist/0.6/xdomain.min.js" master="http://court.atlantaga.gov"></script>');
});

app.get('/', function(req, res) {
  res.send('Hello, I am Courtbot. I have a heart of justice and a knowledge of court cases.');
});

// Fuzzy search that returns cases with a partial name match or
// an exact citation match
app.get('/search', function(req, res) {
  if (!req.query || !req.query.q) return res.send(400);
  db.findPlaceFuzzy(req.query.q).then(function(result) {
    return res.json(result);
  });
});

app.get('/sms', function(req, res) {
  var twiml = new twilio.TwimlResponse();
  var text = req.query.Body.toUpperCase();
  //var text = req.body.Body.toUpperCase();
  db.findPlaceFuzzy(text).then(function(result) {
    //return res.json(result)
    //res.send(twiml.toString());
    var firstRec = _.first(result);
    var resCount = result.length;
    twiml.message('I think you\'re looking for ' + firstRec.contact + '. You can reach them by calling ' + firstRec.phone + ' or going to their site: ' + firstRec.url + '. They are located at ' + firstRec.address + '.');
    twiml.message('FYI - this is off the top of my head, I have ' + (resCount - 1) + ' more potential results, but I\'m still dumb.  I do have big dreams and hope to soon become more than a product of insomnia.');
    // Deploy to keen, return msg:
    keenClient.addEvent('searches', { search: text }, function() {
      return res.send(twiml.toString());
    });
  });
});

// Respond to text messages that come in from Twilio
/*app.post('/sms_old', function(req, res) {
  var twiml = new twilio.TwimlResponse();
  var text = req.body.Body.toUpperCase();

  if (req.session.askedReminder) {
    if (text === 'YES' || text === 'YEA' || text === 'YUP' || text === 'Y') {
      var match = req.session.match;
      db.addReminder({
        caseId: match.id,
        phone: req.body.From,
        originalCase: JSON.stringify(match)
      }, function(err, data) {});

      twiml.sms('Sounds good. We\'ll text you a day before your case. Call us at (404) 954-7914 with any other questions.');
      req.session.askedReminder = false;
      res.send(twiml.toString());
    } else if (text === 'NO' || text ==='N') {
      twiml.sms('Alright, no problem. See you on your court date. Call us at (404) 954-7914 with any other questions.');
      req.session.askedReminder = false;
      res.send(twiml.toString());
    }
  }

  if (req.session.askedQueued) {
    if (text === 'YES' || text === 'YEA' || text === 'YUP' || text === 'Y') {
      db.addQueued({
        citationId: req.session.citationId,
        phone: req.body.From,
      }, function(err, data) {});

      twiml.sms('Sounds good. We\'ll text you in the next 14 days. Call us at (404) 954-7914 with any other questions.');
      req.session.askedQueued = false;
      res.send(twiml.toString());
    } else if (text === 'NO' || text ==='N') {
      twiml.sms('No problem. Call us at (404) 954-7914 with any other questions.');
      req.session.askedQueued = false;
      res.send(twiml.toString());
    }
  }

  db.findCitation(text, function(err, results) {
    // If we can't find the case, or find more than one case with the citation
    // number, give an error and recommend they call in.
    if (!results || results.length === 0 || results.length > 1) {
      var correctLengthCitation = 6 <= text.length && text.length <= 9;
      if (correctLengthCitation) {
        twiml.sms('Couldn\'t find your case. It takes 14 days for new citations to appear in the sytem. Would you like a text when we find your information? (Reply YES or NO)');

        req.session.askedQueued = true;
        req.session.citationId = text;
      } else {
        twiml.sms('Sorry, we couldn\'t find that court case. Please call us at (404) 954-7914.');
      }
    } else {
      var match = results[0];
      var name = cleanupName(match.defendant);
      var date = moment(match.date).format('dddd, MMM Do');

      if (canPayOnline(match)){
        twiml.sms('You can pay now and skip court. Just call (404) 658-6940 or visit court.atlantaga.gov. \n\nOtherwise, your court date is ' + date + ' at ' + match.time +', in courtroom ' + match.room + '.');
      } else {
        twiml.sms('Found a court case for ' + name + ' on ' + date + ' at ' + match.time +', in courtroom ' + match.room +'. Would you like a reminder the day before? (reply YES or NO)');

        req.session.match = match;
        req.session.askedReminder = true;
      }
    }

    res.send(twiml.toString());
  });
});
*/

// You can pay online if ALL your individual citations can be paid online
var canPayOnline = function(courtCase) {
  var eligible = true;
  courtCase.citations.forEach(function(citation) {
    if (citation.payable !== '1') eligible = false;
  });
  return eligible;
};

var cleanupName = function(name) {
  // Switch LAST, FIRST to FIRST LAST
  var bits = name.split(',');
  name = bits[1] + ' ' + bits[0];
  name = name.trim();

  // Change FIRST LAST to First Last
  name = name.replace(/\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });

  return name;
};

var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
  console.log("Listening on " + port);
});

<commit_msg>Cleanup.<commit_after>
if (!process.env.NODE_ENV)
  var dotenv = require('dotenv').load();

var twilio = require('twilio');
var Keen = require('keen.io');
var _ = require('lodash');
var express = require('express');
var logfmt = require('logfmt');
var moment = require('moment');
var Promise = require('bluebird');
var db = require('./db');
var app = express();

var keenClient = Keen.configure({
  projectId: process.env.KEEN_PROJECT_ID,
  writeKey: process.env.KEEN_WRITE_KEY
});

// Express Middleware
app.use(logfmt.requestLogger());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser(process.env.COOKIE_SECRET));
app.use(express.cookieSession());

// Allows CORS
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});

// Enable CORS support for IE8.
app.get('/proxy.html', function(req, res) {
  res.send('<!DOCTYPE HTML>\n' + '<script src="http://jpillora.com/xdomain/dist/0.6/xdomain.min.js" master="http://court.atlantaga.gov"></script>');
});

app.get('/', function(req, res) {
  res.send('Hello, I am Courtbot. I have a heart of justice and a knowledge of court cases.');
});

// Fuzzy search that returns cases with a partial name match or
// an exact citation match
app.get('/search', function(req, res) {
  if (!req.query || !req.query.q) return res.send(400);
  db.findPlaceFuzzy(req.query.q).then(function(result) {
    return res.json(result);
  });
});

app.get('/sms', function(req, res) {
  var twiml = new twilio.TwimlResponse();
  var text = req.query.Body.toUpperCase();
  db.findPlaceFuzzy(text).then(function(result) {
    var firstRec = _.first(result);
    var resCount = result.length;
    twiml.message('I think you\'re looking for ' + firstRec.contact + '. You can reach them by calling ' + firstRec.phone + ' or going to their site: ' + firstRec.url + '. They are located at ' + firstRec.address + '.');
    twiml.message('FYI - this is off the top of my head, I have ' + (resCount - 1) + ' more potential results, but I\'m still dumb.  I do have big dreams and hope to soon become more than a product of insomnia.');
    // Deploy to keen, return msg:
    keenClient.addEvent('searches', { search: text }, function() {
      return res.send(twiml.toString());
    });
  });
});

// Respond to text messages that come in from Twilio
/*app.post('/sms_old', function(req, res) {
  var twiml = new twilio.TwimlResponse();
  var text = req.body.Body.toUpperCase();

  if (req.session.askedReminder) {
    if (text === 'YES' || text === 'YEA' || text === 'YUP' || text === 'Y') {
      var match = req.session.match;
      db.addReminder({
        caseId: match.id,
        phone: req.body.From,
        originalCase: JSON.stringify(match)
      }, function(err, data) {});

      twiml.sms('Sounds good. We\'ll text you a day before your case. Call us at (404) 954-7914 with any other questions.');
      req.session.askedReminder = false;
      res.send(twiml.toString());
    } else if (text === 'NO' || text ==='N') {
      twiml.sms('Alright, no problem. See you on your court date. Call us at (404) 954-7914 with any other questions.');
      req.session.askedReminder = false;
      res.send(twiml.toString());
    }
  }

  if (req.session.askedQueued) {
    if (text === 'YES' || text === 'YEA' || text === 'YUP' || text === 'Y') {
      db.addQueued({
        citationId: req.session.citationId,
        phone: req.body.From,
      }, function(err, data) {});

      twiml.sms('Sounds good. We\'ll text you in the next 14 days. Call us at (404) 954-7914 with any other questions.');
      req.session.askedQueued = false;
      res.send(twiml.toString());
    } else if (text === 'NO' || text ==='N') {
      twiml.sms('No problem. Call us at (404) 954-7914 with any other questions.');
      req.session.askedQueued = false;
      res.send(twiml.toString());
    }
  }

  db.findCitation(text, function(err, results) {
    // If we can't find the case, or find more than one case with the citation
    // number, give an error and recommend they call in.
    if (!results || results.length === 0 || results.length > 1) {
      var correctLengthCitation = 6 <= text.length && text.length <= 9;
      if (correctLengthCitation) {
        twiml.sms('Couldn\'t find your case. It takes 14 days for new citations to appear in the sytem. Would you like a text when we find your information? (Reply YES or NO)');

        req.session.askedQueued = true;
        req.session.citationId = text;
      } else {
        twiml.sms('Sorry, we couldn\'t find that court case. Please call us at (404) 954-7914.');
      }
    } else {
      var match = results[0];
      var name = cleanupName(match.defendant);
      var date = moment(match.date).format('dddd, MMM Do');

      if (canPayOnline(match)){
        twiml.sms('You can pay now and skip court. Just call (404) 658-6940 or visit court.atlantaga.gov. \n\nOtherwise, your court date is ' + date + ' at ' + match.time +', in courtroom ' + match.room + '.');
      } else {
        twiml.sms('Found a court case for ' + name + ' on ' + date + ' at ' + match.time +', in courtroom ' + match.room +'. Would you like a reminder the day before? (reply YES or NO)');

        req.session.match = match;
        req.session.askedReminder = true;
      }
    }

    res.send(twiml.toString());
  });
});
*/

// You can pay online if ALL your individual citations can be paid online
var canPayOnline = function(courtCase) {
  var eligible = true;
  courtCase.citations.forEach(function(citation) {
    if (citation.payable !== '1') eligible = false;
  });
  return eligible;
};

var cleanupName = function(name) {
  // Switch LAST, FIRST to FIRST LAST
  var bits = name.split(',');
  name = bits[1] + ' ' + bits[0];
  name = name.trim();

  // Change FIRST LAST to First Last
  name = name.replace(/\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });

  return name;
};

var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
  console.log("Listening on " + port);
});

<|endoftext|>


<commit_before>// web.js
var express = require("express");
var logfmt = require("logfmt");
var mongo = require('mongodb');

var app = express();

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost:27017/';
  // console.log(mongoUri);

app.use(logfmt.requestLogger());
app.use(express.urlencoded());
app.get('/', function(req, res) {
  res.sendfile('./main.html');
});

app.get(/^\/([\d\w]+)$/, function(req, res) {
	mongo.Db.connect(mongoUri, function (err, db) {
		db.collection('urls', function(er, collection) {
			collection.find({"short": req.params[0]}).toArray(function( err, docs) {
				if (docs.length) {
					res.redirect(docs[0].url);
				} else {
					res.send('Sorry not found.');
				}
			});
		});
	});
});

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

	mongo.Db.connect(mongoUri, function (err, db) {

		db.collection('ref_seq', function(er, collection) {

			collection.findAndModify({ _id: "seq"}, {}, { $inc: { seq: 1 }},
									 {}, function(err, object) {

				db.collection('urls', insertNewShortened);
			});
		});
	});
});

function insertNewShortened(err, collection) {
	collection = arguments[1];
	var url = req.query.url;
	var newLink = genID(object.seq);
	collection.insert({"short": newLink, "url": url}, sendToShortened);
}

function sendToShortened() {
	res.send(genResponse(newLink));
}

var port = process.env.PORT || 5000;
app.listen(port, function() {
  console.log("Listening on " + port);
});

function genResponse(link) {
	return 'here\'s your link: quiet-scrubland' +
			'-5884.herokuapp.com/'  + link + '';
}

function genID(decimal, symbols) {
	if (typeof symbols === 'undefined' || !symbols.length) {
		var symbols = ['0','1','2','3','4','5','6','7','8',
				   '9','b','c','d','f','g','h',
				   'j','k','n','p','q',
				   'r','s','t','w','x','y','z'];
	}
	decimal = decimal * 25;

	function pow(power) {
		return Math.pow(symbols.length, power);
	}

	var numstr = '';
	var rem;
	var i = 0;
	while (true) {

		if ( decimal/pow(i+1) < 1) {
			break;
		}
		i++;

	}

	while ( i >= 0 ) {

		var leftMost = symbols[Math.floor(decimal / pow(i))];
		numstr += leftMost;
		decimal = decimal - pow(i) * Math.floor(decimal / pow(i));
		i--;
	}

	return numstr;
}<commit_msg>unrolling callback chain<commit_after>// web.js
var express = require("express");
var logfmt = require("logfmt");
var mongo = require('mongodb');

var app = express();

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost:27017/';
  // console.log(mongoUri);

app.use(logfmt.requestLogger());
app.use(express.urlencoded());
app.get('/', function(req, res) {
  res.sendfile('./main.html');
});

app.get(/^\/([\d\w]+)$/, function(req, res) {
	mongo.Db.connect(mongoUri, function (err, db) {
		db.collection('urls', function(er, collection) {
			collection.find({"short": req.params[0]}).toArray(function( err, docs) {
				if (docs.length) {
					res.redirect(docs[0].url);
				} else {
					res.send('Sorry not found.');
				}
			});
		});
	});
});

app.get('/addurl/', function(req, res) {
	var url = req.query.url;
	mongo.Db.connect(mongoUri, function (err, db) {

		db.collection('ref_seq', function(er, collection) {

			collection.findAndModify({ _id: "seq"}, {}, { $inc: { seq: 1 }},
									 {}, function(err, object) {
				var newLink = genID(doc.seq);
				db.collection('urls', insertNewShortened);
			});
		});
	});
});

function insertNewShortened(err, collection) {
	collection = arguments[1];
	collection.insert({"short": newLink, "url": url}, sendToShortened);
}

function sendToShortened() {
	res.send(genResponse(newLink));
}

var port = process.env.PORT || 5000;
app.listen(port, function() {
  console.log("Listening on " + port);
});

function genResponse(link) {
	return 'here\'s your link: quiet-scrubland' +
			'-5884.herokuapp.com/'  + link + '';
}

function genID(decimal, symbols) {
	if (typeof symbols === 'undefined' || !symbols.length) {
		var symbols = ['0','1','2','3','4','5','6','7','8',
				   '9','b','c','d','f','g','h',
				   'j','k','n','p','q',
				   'r','s','t','w','x','y','z'];
	}
	decimal = decimal * 25;

	function pow(power) {
		return Math.pow(symbols.length, power);
	}

	var numstr = '';
	var rem;
	var i = 0;
	while (true) {

		if ( decimal/pow(i+1) < 1) {
			break;
		}
		i++;

	}

	while ( i >= 0 ) {

		var leftMost = symbols[Math.floor(decimal / pow(i))];
		numstr += leftMost;
		decimal = decimal - pow(i) * Math.floor(decimal / pow(i));
		i--;
	}

	return numstr;
}<|endoftext|>


<commit_before>// web.js

var express = require("express");
var logfmt = require("logfmt");
var path = require('path');
var favicon = require('static-favicon');
//var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var request = require("request");

var mongo = require('mongodb');

// trying to parse json out of the url... may not need all of these packages
var url = require('url');
var querystring = require('querystring');
// express-specific answer that makes the above libaries unnecessary -
// http://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-node-js?rq=1

// this first section was (part of) how to hook up to local mongodb
/*var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/tutorial3data');
*/

// see this link for extremely brief tutorial on setting up mongodb with heroku/node - this may not use monk
// https://devcenter.heroku.com/articles/getting-started-with-nodejs#using-mongodb

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/mydb';

  // this works, but inserts a dummy record. mimic this if you want to do shit
/*
mongo.Db.connect(mongoUri, function (err, db) {
  db.collection('mydocs', function(er, collection) {
    collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) {  });
  });
});
*/

var app = express();

app.use(logfmt.requestLogger());

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

app.get('/', function(req, res) {
  res.send("Ello chap. Get Rowdy.");
});

// default page to render at  basic url
app.get('/generate_test_map/*', function(req, res) {
/*
request({url: req.url,json: true}, function(err, resp, body) {
	    res.send(body);
	}
);
*/
/*
var input_query = url.parse(req.url).query;
var latitude = substr(input_query, input_query.indexof("&"));
var longitude = substr(input_qery, input_query.indexof("&"), input_qery.length);

res.send("Latitude: " + latitude + " Longitude: " + longitude);
*/

var url_json_return = querystring.parse(url.parse(req.url).query);

//res.send("Latitude: " + url_json_return.latitude + " Longitude: " + url_json_return.longitude);
res.send("Latitude: " + req.query.latitude + " Longitude: " + req.query.longitude);

  //res.send("Fucking miles says: " + url.parse(req.url).query + ".... fucking miles...");

  //var 	abcdefg = JSON.parse(url.parse(req.url).query);
  	//console.log(url.parse(req.url).query);
  	 //);
  //res.render('basic_google_map.html');
});

// Set view engine to html files in the /views/ directory. Path.join makes
// it environment independent ('/' vs '\')
app.set('views', path.join(__dirname, '/views'));

// Not sure why/how etc. but 'ejs' is what lets you use html files
app.engine('html', require('ejs').renderFile);

// this was for local running, with jade files. Not needed using ember and HTML
//app.set('view engine', 'jade');

// navigate to {default url}/basic_google_map and render basic_google_map.html
app.get('/basic_google_map', function(req, res) {
  res.render('basic_google_map.html');
});

// This is for heroku, don't change the port
var port = Number(process.env.PORT || 5000);

app.listen(port, function() {
  console.log("Listening on " + port);
});

<commit_msg>adding some extremely simple error checking to lat/long url checking<commit_after>// web.js

var express = require("express");
var logfmt = require("logfmt");
var path = require('path');
var favicon = require('static-favicon');
//var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var request = require("request");

var mongo = require('mongodb');

// trying to parse json out of the url... may not need all of these packages
//var url = require('url');
//var querystring = require('querystring');

// express-specific answer that makes the above libaries unnecessary -
// http://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-node-js?rq=1

// this first section was (part of) how to hook up to local mongodb
/*var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/tutorial3data');
*/

// see this link for extremely brief tutorial on setting up mongodb with heroku/node - this may not use monk
// https://devcenter.heroku.com/articles/getting-started-with-nodejs#using-mongodb

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/mydb';

  // this works, but inserts a dummy record. mimic this if you want to do shit
/*
mongo.Db.connect(mongoUri, function (err, db) {
  db.collection('mydocs', function(er, collection) {
    collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) {  });
  });
});
*/

var app = express();

// not exactly sure what this does, it is from heroku nodejs tutorial / getting started
app.use(logfmt.requestLogger());

// default page to render at  basic url
app.get('/', function(req, res) {
  res.send("Ello chap. Get Rowdy.");
});

// testing JSON creation using Lat-Long
app.get('/generate_test_map/*', function(req, res) {

// the below two lines are one way to do url parsing to JSON if you aren't using express
//var url_json_return = querystring.parse(url.parse(req.url).query);
//res.send("Latitude: " + url_json_return.latitude + " Longitude: " + url_json_return.longitude);
if (req.query.hasOwnProperty('latitude') && req.query.hasOwnProperty('longitude') )
   {
     res.send("Latitude: " + req.query.latitude + " Longitude: " + req.query.longitude);
   }
else
   {
	 res.send("You didn't give latitude and longitude. check spelling/case of keys");
   }
});

// Set view engine to html files in the /views/ directory. Path.join makes
// it environment independent ('/' vs '\')
app.set('views', path.join(__dirname, '/views'));

// Not sure why/how etc. but 'ejs' is what lets you use html files
app.engine('html', require('ejs').renderFile);

// this was for local running, with jade files. Not needed using ember and HTML
//app.set('view engine', 'jade');

// navigate to {default url}/basic_google_map and render basic_google_map.html
app.get('/basic_google_map', function(req, res) {
  res.render('basic_google_map.html');
});

// This is for heroku, don't change the port
var port = Number(process.env.PORT || 5000);

app.listen(port, function() {
  console.log("Listening on " + port);
});

<|endoftext|>


<commit_before>// functions.js

var express = require('express'),
    Parse = require('parse/node').Parse,
    PromiseRouter = require('./PromiseRouter'),
    rest = require('./rest');

var router = new PromiseRouter();

function handleCloudFunction(req) {
  if (Parse.Cloud.Functions[req.params.functionName]) {
    return new Promise(function (resolve, reject) {
      var response = createResponseObject(resolve, reject);
      var request = {
        params: req.body || {},
        master: req.auth && req.auth.isMaster,
        user: req.auth && req.auth.user,
      };
      Parse.Cloud.Functions[req.params.functionName](request, response);
    });
  } else {
    throw new Parse.Error(Parse.Error.SCRIPT_FAILED, 'Invalid function.');
  }
}

function createResponseObject(resolve, reject) {
  return {
    success: function(result) {
      resolve({
        response: {
          result: result
        }
      });
    },
    error: function(error) {
      reject(new Parse.Error(Parse.Error.SCRIPT_FAILED, error));
    }
  }
}

router.route('POST', '/functions/:functionName', handleCloudFunction);

module.exports = router;
<commit_msg>Correct function response encoding<commit_after>// functions.js

var express = require('express'),
    Parse = require('parse/node').Parse,
    PromiseRouter = require('./PromiseRouter'),
    rest = require('./rest');

var router = new PromiseRouter();

function handleCloudFunction(req) {
  if (Parse.Cloud.Functions[req.params.functionName]) {
    return new Promise(function (resolve, reject) {
      var response = createResponseObject(resolve, reject);
      var request = {
        params: req.body || {},
        master: req.auth && req.auth.isMaster,
        user: req.auth && req.auth.user,
      };
      Parse.Cloud.Functions[req.params.functionName](request, response);
    });
  } else {
    throw new Parse.Error(Parse.Error.SCRIPT_FAILED, 'Invalid function.');
  }
}

function createResponseObject(resolve, reject) {
  return {
    success: function(result) {
      resolve({
        response: {
          result: Parse._encode(result)
        }
      });
    },
    error: function(error) {
      reject(new Parse.Error(Parse.Error.SCRIPT_FAILED, error));
    }
  }
}

router.route('POST', '/functions/:functionName', handleCloudFunction);

module.exports = router;
<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
    'ngRoute',
    'myApp.view1',
    'myApp.view2',
    'myApp.view3',
    'myApp.view4',
    'myApp.view5',
    'myApp.view6',
    'myApp.view7',
    'myApp.version'
]).config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
    $locationProvider.hashPrefix('!');

    $routeProvider.otherwise({redirectTo: '/view1'});
}]).service('usage', [function () {
    /**
     * Data to use to populate graph - shows peek usage of a coffee shop
     */
    return {
        "coffeeShop": [
            {
                "date": 1490155200000,
                "data": [
                    {
                        "time": 901,
                        "usage": 1000
                    },
                    {
                        "time": 1001,
                        "usage": 2000
                    },
                    {
                        "time": 1101,
                        "usage": 3000
                    },
                    {
                        "time": 1201,
                        "usage": 4000
                    },
                    {
                        "time": 1301,
                        "usage": 5000
                    },
                    {
                        "time": 1401,
                        "usage": 6000
                    },
                    {
                        "time": 1501,
                        "usage": 7000
                    },
                    {
                        "time": 1601,
                        "usage": 8000
                    }
                ]
            },
            {
                "date": 1490241600000,
                "data": [
                    {
                        "time": 902,
                        "usage": 1000
                    },
                    {
                        "time": 1002,
                        "usage": 2000
                    },
                    {
                        "time": 1102,
                        "usage": 3000
                    },
                    {
                        "time": 1202,
                        "usage": 4000
                    },
                    {
                        "time": 1302,
                        "usage": 5000
                    },
                    {
                        "time": 1402,
                        "usage": 6000
                    },
                    {
                        "time": 1502,
                        "usage": 7000
                    },
                    {
                        "time": 1602,
                        "usage": 8000
                    }
                ]
            },
            {
                "date": 1490328000000,
                "data": [
                    {
                        "time": 903,
                        "usage": 1000
                    },
                    {
                        "time": 1003,
                        "usage": 2000
                    },
                    {
                        "time": 1103,
                        "usage": 3000
                    },
                    {
                        "time": 1203,
                        "usage": 4000
                    },
                    {
                        "time": 1303,
                        "usage": 5000
                    },
                    {
                        "time": 1403,
                        "usage": 6000
                    },
                    {
                        "time": 1503,
                        "usage": 7000
                    },
                    {
                        "time": 1603,
                        "usage": 8000
                    }
                ]
            },
            {
                "date": 1490414400000,
                "data": [
                    {
                        "time": 904,
                        "usage": 1000
                    },
                    {
                        "time": 1004,
                        "usage": 2000
                    },
                    {
                        "time": 1104,
                        "usage": 3000
                    },
                    {
                        "time": 1204,
                        "usage": 4000
                    },
                    {
                        "time": 1304,
                        "usage": 5000
                    },
                    {
                        "time": 1404,
                        "usage": 6000
                    },
                    {
                        "time": 1504,
                        "usage": 7000
                    },
                    {
                        "time": 1604,
                        "usage": 8000
                    }
                ]
            }
        ]
    };

}]);
<commit_msg>Changed graph usage to vary instead of incrementing 1000 each time.<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
    'ngRoute',
    'myApp.view1',
    'myApp.view2',
    'myApp.view3',
    'myApp.view4',
    'myApp.view5',
    'myApp.view6',
    'myApp.view7',
    'myApp.version'
]).config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
    $locationProvider.hashPrefix('!');

    $routeProvider.otherwise({redirectTo: '/view1'});
}]).service('usage', [function () {
    /**
     * Data to use to populate graph - shows peek usage of a coffee shop
     */
    return {
        "coffeeShop": [
            {
                "date": 1490155200000,
                "data": [
                    {
                        "time": 901,
                        "usage": 7000
                    },
                    {
                        "time": 1001,
                        "usage": 2000
                    },
                    {
                        "time": 1101,
                        "usage": 4000
                    },
                    {
                        "time": 1201,
                        "usage": 3000
                    },
                    {
                        "time": 1301,
                        "usage": 5000
                    },
                    {
                        "time": 1401,
                        "usage": 9000
                    },
                    {
                        "time": 1501,
                        "usage": 8000
                    },
                    {
                        "time": 1601,
                        "usage": 7500
                    }
                ]
            },
            {
                "date": 1490241600000,
                "data": [
                    {
                        "time": 902,
                        "usage": 1000
                    },
                    {
                        "time": 1002,
                        "usage": 2000
                    },
                    {
                        "time": 1102,
                        "usage": 3000
                    },
                    {
                        "time": 1202,
                        "usage": 4000
                    },
                    {
                        "time": 1302,
                        "usage": 5000
                    },
                    {
                        "time": 1402,
                        "usage": 6000
                    },
                    {
                        "time": 1502,
                        "usage": 7000
                    },
                    {
                        "time": 1602,
                        "usage": 8000
                    }
                ]
            },
            {
                "date": 1490328000000,
                "data": [
                    {
                        "time": 903,
                        "usage": 1000
                    },
                    {
                        "time": 1003,
                        "usage": 2000
                    },
                    {
                        "time": 1103,
                        "usage": 3000
                    },
                    {
                        "time": 1203,
                        "usage": 4000
                    },
                    {
                        "time": 1303,
                        "usage": 5000
                    },
                    {
                        "time": 1403,
                        "usage": 6000
                    },
                    {
                        "time": 1503,
                        "usage": 7000
                    },
                    {
                        "time": 1603,
                        "usage": 8000
                    }
                ]
            },
            {
                "date": 1490414400000,
                "data": [
                    {
                        "time": 904,
                        "usage": 1000
                    },
                    {
                        "time": 1004,
                        "usage": 2000
                    },
                    {
                        "time": 1104,
                        "usage": 3000
                    },
                    {
                        "time": 1204,
                        "usage": 4000
                    },
                    {
                        "time": 1304,
                        "usage": 5000
                    },
                    {
                        "time": 1404,
                        "usage": 6000
                    },
                    {
                        "time": 1504,
                        "usage": 7000
                    },
                    {
                        "time": 1604,
                        "usage": 8000
                    }
                ]
            }
        ]
    };

}]);
<|endoftext|>


<commit_before>let express = require('express')
let morgan = require('morgan')
let cookieParser = require('cookie-parser')
let bodyParser = require('body-parser')
let path = require('path')
let routes = require('./routes/routes')
let Server = require('http').Server
let browserify = require('browserify-middleware')
let session = require('express-session')
let MongoStore = require('connect-mongo')(session)
let mongoose = require('mongoose')
let flash = require('connect-flash')
let io = require('socket.io')

require('songbird')

let passportMiddleWare = require('./middlewares/passport')
const NODE_ENV = process.env.NODE_ENV || 'development'
let people = {}
let connectedSockets = {}

class App {

	constructor (config) {
		let app = this.app = express()
		this.port = process.env.PORT || 8000

		app.config = {
			auth: config.auth[NODE_ENV],
			database: config.database[NODE_ENV]
		}

		// configure passport
		passportMiddleWare.configure(config.auth[NODE_ENV])
		app.passport = passportMiddleWare.passport

		// connect database
		mongoose.connect(config.database[NODE_ENV].url)

		// configure other middleware
		app.use(morgan('dev'))
		app.use(cookieParser('canvas-chat-session'))
		app.use(bodyParser.json())
		app.use(bodyParser.urlencoded({extended : true }))

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

		this.sessionMiddleware = session({
			secret: 'canvas-chat-session',
			store: new MongoStore({db:'canvas-chat'}),
			resave: true,
			saveUninitialized: true
		})

		app.use(this.sessionMiddleware)

		// Setup passport authentication middleware
		app.use(app.passport.initialize())
		// persistent login sessions
		app.use(app.passport.session())
		// Flash messages stored in session
		app.use(flash())

		routes(this.app)

		// browserify client scripts
		browserify.settings({transform: ['babelify']})
        app.use(express.static('public'))

        // TODO find a way to bundle all files together
        // login/main.js
        app.use('/login/main.js', browserify('./public/js/login/main.js'))
        // TODO: profile/main.js
        app.use('/profile/main.js', browserify('./public/js/profile/main.js'))
        app.use('/chat/main.js', browserify('./public/js/chat/main.js'))

        // TODO: chatroom/main.js

		this.server = Server(app)
		this.server = Server(app)
        this.io = io(this.server)
        this.io.use((socket, next) => {
			this.sessionMiddleware(socket.request, socket.request.res, next)
        })
        this.io.on('connection', socket => {
        	console.log('a user connected using socket')
        	socket.on('disconnect', () => {
        		delete connectedSockets[socket.id]
        		delete people[socket.username]
        		console.log('user disconnected')
        	})
        	socket.on('addUser', (facebookId) => {
            	console.log(facebookId, socket.id)
				socket.username = facebookId
				people[socket.username] = socket.id
				connectedSockets[socket.id] = socket
            })

			socket.on('attributes', (response) => {
				let toSocketId = people[response.to]
				if(toSocketId) {
					console.log('server attributes', response)
					connectedSockets[toSocketId].emit('server:attributes', response)
				}
			})

			socket.on('client:erase-canvas', (update) => {
				let toSocketId = people[update.to]
				if (toSocketId) {
					connectedSockets[toSocketId].emit('server:erase-canvas', update)
				}
			})

			socket.on('client:image-upload', (update) => {
				console.log('image upload server', update)
				let toSocketId = people[update.to]
				if (toSocketId) {
					connectedSockets[toSocketId].emit('server:image-upload', update)
				}
			})

			socket.on("PATH", (response) => {
				let toSocketId = people[response.to]
				if(toSocketId) {
					console.log('server PATH', response)
					connectedSockets[toSocketId].emit('server:PATH', response)
				}
			})
			socket.on("MOVE", (response) => {
				let toSocketId = people[response.to]
				if(toSocketId) {
					console.log('server MOVE', response)
					connectedSockets[toSocketId].emit('server:MOVE', response)
				}
			})
        })

	}

	async initialize(port) {
		await this.server.promise.listen(port)
		return this
	}
}

module.exports = App<commit_msg>Upload large files<commit_after>let express = require('express')
let morgan = require('morgan')
let cookieParser = require('cookie-parser')
let bodyParser = require('body-parser')
let path = require('path')
let routes = require('./routes/routes')
let Server = require('http').Server
let browserify = require('browserify-middleware')
let session = require('express-session')
let MongoStore = require('connect-mongo')(session)
let mongoose = require('mongoose')
let flash = require('connect-flash')
let io = require('socket.io')

require('songbird')

let passportMiddleWare = require('./middlewares/passport')
const NODE_ENV = process.env.NODE_ENV || 'development'
let people = {}
let connectedSockets = {}

class App {

	constructor (config) {
		let app = this.app = express()
		this.port = process.env.PORT || 8000

		app.config = {
			auth: config.auth[NODE_ENV],
			database: config.database[NODE_ENV]
		}

		// configure passport
		passportMiddleWare.configure(config.auth[NODE_ENV])
		app.passport = passportMiddleWare.passport

		// connect database
		mongoose.connect(config.database[NODE_ENV].url)

		// configure other middleware
		app.use(morgan('dev'))
		app.use(cookieParser('canvas-chat-session'))
		app.use(bodyParser.json({limit: '50mb'}))
		app.use(bodyParser.urlencoded({limit: '50mb', extended : true }))

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

		this.sessionMiddleware = session({
			secret: 'canvas-chat-session',
			store: new MongoStore({db:'canvas-chat'}),
			resave: true,
			saveUninitialized: true
		})

		app.use(this.sessionMiddleware)

		// Setup passport authentication middleware
		app.use(app.passport.initialize())
		// persistent login sessions
		app.use(app.passport.session())
		// Flash messages stored in session
		app.use(flash())

		routes(this.app)

		// browserify client scripts
		browserify.settings({transform: ['babelify']})
        app.use(express.static('public'))

        // TODO find a way to bundle all files together
        // login/main.js
        app.use('/login/main.js', browserify('./public/js/login/main.js'))
        // TODO: profile/main.js
        app.use('/profile/main.js', browserify('./public/js/profile/main.js'))
        app.use('/chat/main.js', browserify('./public/js/chat/main.js'))

        // TODO: chatroom/main.js

		this.server = Server(app)
		this.server = Server(app)
        this.io = io(this.server)
        this.io.use((socket, next) => {
			this.sessionMiddleware(socket.request, socket.request.res, next)
        })
        this.io.on('connection', socket => {
        	console.log('a user connected using socket')
        	socket.on('disconnect', () => {
        		delete connectedSockets[socket.id]
        		delete people[socket.username]
        		console.log('user disconnected')
        	})
        	socket.on('addUser', (facebookId) => {
            	console.log(facebookId, socket.id)
				socket.username = facebookId
				people[socket.username] = socket.id
				connectedSockets[socket.id] = socket
            })

			socket.on('attributes', (response) => {
				let toSocketId = people[response.to]
				if(toSocketId) {
					console.log('server attributes', response)
					connectedSockets[toSocketId].emit('server:attributes', response)
				}
			})

			socket.on('client:erase-canvas', (update) => {
				let toSocketId = people[update.to]
				if (toSocketId) {
					connectedSockets[toSocketId].emit('server:erase-canvas', update)
				}
			})

			socket.on('client:image-upload', (update) => {
				console.log('image upload server', update)
				let toSocketId = people[update.to]
				if (toSocketId) {
					connectedSockets[toSocketId].emit('server:image-upload', update)
				}
			})

			socket.on("PATH", (response) => {
				let toSocketId = people[response.to]
				if(toSocketId) {
					console.log('server PATH', response)
					connectedSockets[toSocketId].emit('server:PATH', response)
				}
			})
			socket.on("MOVE", (response) => {
				let toSocketId = people[response.to]
				if(toSocketId) {
					console.log('server MOVE', response)
					connectedSockets[toSocketId].emit('server:MOVE', response)
				}
			})
        })

	}

	async initialize(port) {
		await this.server.promise.listen(port)
		return this
	}
}

module.exports = App<|endoftext|>


<commit_before>var gui = require('nw.gui');
var win = gui.Window.get();
var nativeMenuBar = new gui.Menu({ type: "menubar" });
nativeMenuBar.createMacBuiltin('chrome devtools app');
win.menu = nativeMenuBar;

var app = angular.module('app', ['ngAnimate', 'ngMaterial']);

app.filter('regex', function() {
    return function(input, field, regex) {
        var patt = new RegExp(regex);
        var out = [];

        if(input) {
            for (var i = 0; i < input.length; i++){
                if(patt.test(input[i][field])) {
                    out.push(input[i]);
                }
            }
        }

        return out;
    };
});

app.directive('devtools', function() {

    return {
        restrict: 'E',
        replace: true,
        template: '

',
        scope: {
            'src': '@',
        },
        link: function ($scope, element, attr) {

        }
    }

});

app.controller('home', function ($scope, $http, $location) {

    $scope.filter = '^page$';
    $scope.targetsFilterSelectedIndex = 1;
    $scope.targets = [];
    $scope.devtoolsUrl = '';

    $scope.debug = function() {

        var gui = require('nw.gui');
        var win = gui.Window.get();

        win.showDevTools();
    }

    $scope.connect = function(target) {

        if(!target.devtoolsFrontendUrl) {
            return;
        }

        var frontendUrl = target.devtoolsFrontendUrl.replace('/devtools/', '');

        $scope.devtoolsUrl = 'devtools/front_end/' + frontendUrl
    }

    $scope.setTargetFilter = function(filter) {

        switch(filter) {
            case 'apps':
                $scope.filter = '^apps$';
                $scope.targetsFilterSelectedIndex = 0;
                break;
            case 'pages':
                $scope.filter = '^page$';
                $scope.targetsFilterSelectedIndex = 1;
                break;
            case 'background_page':
                $scope.filter = '^background_page$';
                $scope.targetsFilterSelectedIndex = 2;
                break;
        }

    }

    $scope.discover = function() {
        var req = $http.get('http://localhost:9222/json');
        // var req = $http.get('/json.json');

        req.success(function(data, status, headers, config) {
            $scope.targets = data;
        });

        req.catch(function() {

        });
    }

    $scope.showTargets = function() {
        $scope.devtoolsUrl = '';
    }

    $scope.discover();

});
<commit_msg>moves gui setup into controller<commit_after>
var app = angular.module('app', ['ngAnimate', 'ngMaterial']);

app.filter('regex', function() {
    return function(input, field, regex) {
        var patt = new RegExp(regex);
        var out = [];

        if(input) {
            for (var i = 0; i < input.length; i++){
                if(patt.test(input[i][field])) {
                    out.push(input[i]);
                }
            }
        }

        return out;
    };
});

app.directive('devtools', function() {

    return {
        restrict: 'E',
        replace: true,
        template: '

',
        scope: {
            'src': '@',
        },
        link: function ($scope, element, attr) {

        }
    }

});

app.controller('home', function ($scope, $http, $location) {

    $scope.filter = '^page$';
    $scope.targetsFilterSelectedIndex = 1;
    $scope.targets = [];
    $scope.devtoolsUrl = '';

    $scope.gui = require('nw.gui');
    $scope.win = $scope.gui.Window.get();

    var nativeMenuBar = new $scope.gui.Menu({ type: "menubar" });
    nativeMenuBar.createMacBuiltin('chrome devtools app');

    $scope.win.menu = nativeMenuBar;

    $scope.debug = function() {
        $scope.win.showDevTools();
    }

    $scope.connect = function(target) {

        if(!target.devtoolsFrontendUrl) {
            return;
        }

        var frontendUrl = target.devtoolsFrontendUrl.replace('/devtools/', '');

        $scope.devtoolsUrl = 'devtools/front_end/' + frontendUrl
    }

    $scope.setTargetFilter = function(filter) {

        switch(filter) {
            case 'apps':
                $scope.filter = '^apps$';
                $scope.targetsFilterSelectedIndex = 0;
                break;
            case 'pages':
                $scope.filter = '^page$';
                $scope.targetsFilterSelectedIndex = 1;
                break;
            case 'background_page':
                $scope.filter = '^background_page$';
                $scope.targetsFilterSelectedIndex = 2;
                break;
        }

    }

    $scope.discover = function() {
        var req = $http.get('http://localhost:9222/json');
        // var req = $http.get('/json.json');

        req.success(function(data, status, headers, config) {
            $scope.targets = data;
        });

        req.catch(function() {

        });
    }

    $scope.showTargets = function() {
        $scope.devtoolsUrl = '';
    }

    $scope.discover();

});
<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
    'ngRoute',
    'ui.bootstrap',
    'home',
    'facebook',
    'dondeEstamos',
    'contactanos',
    'quienesSomos',
    'participa'
]).config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/home', {
        templateUrl: '/home/home.html',
        controller: 'HomeCtrl'
    }).when('/dondeEstamos', {
        templateUrl: '/dondeEstamos/dondeEstamos.html',
        controller: 'DondeEstamosCtrl'
    }).when('/contactanos', {
        templateUrl: '/contactanos/contactanos.html',
        controller: 'ContactanosCtrl'
    }).when('/quienesSomos', {
        templateUrl: '/quienesSomos/quienesSomos.html',
        controller: 'QuienesSomosCtrl'
    }).when('/participa', {
        templateUrl: '/participa/participa.html',
        controller: 'ParticipaCtrl'
    }).otherwise({redirectTo: '/home'});

}]);

var app = angular.module('myApp');
app.run(['$rootScope', '$window',
    function($rootScope, $window) {

        $rootScope.user = {};

        $window.fbAsyncInit = function() {
            // Executed when the SDK is loaded

            FB.init({

                /*
                 The app id of the web app;
                 To register a new app visit Facebook App Dashboard
                 ( https://developers.facebook.com/apps/ )
                 */

                appId: '174931712664653',

                /*
                 Adding a Channel File improves the performance
                 of the javascript SDK, by addressing issues
                 with cross-domain communication in certain browsers.
                 */

                //channelUrl: 'app/channel.html',

                /*
                 Set if you want to check the authentication status
                 at the start up of the app
                 */

                status: true,

                /*
                 Enable cookies to allow the server to access
                 the session
                 */

                cookie: true,

                /* Parse XFBML */

                xfbml: true,

                version: 'v2.3'
            });

        };

        // Are you familiar to IIFE ( http://bit.ly/iifewdb ) ?

        (function(d){
            // load the Facebook javascript SDK

            var js,
                id = 'facebook-jssdk',
                ref = d.getElementsByTagName('script')[0];

            if (d.getElementById(id)) {
                return;
            }

            js = d.createElement('script');
            js.id = id;
            js.async = true;
            js.src = "//connect.facebook.net/es_LA/sdk.js";

            ref.parentNode.insertBefore(js, ref);

        }(document));

    }]);
<commit_msg>removed facebook as an app dependency<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
    'ngRoute',
    'ui.bootstrap',
    'home',
    'dondeEstamos',
    'contactanos',
    'quienesSomos',
    'participa'
]).config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/home', {
        templateUrl: '/home/home.html',
        controller: 'HomeCtrl'
    }).when('/dondeEstamos', {
        templateUrl: '/dondeEstamos/dondeEstamos.html',
        controller: 'DondeEstamosCtrl'
    }).when('/contactanos', {
        templateUrl: '/contactanos/contactanos.html',
        controller: 'ContactanosCtrl'
    }).when('/quienesSomos', {
        templateUrl: '/quienesSomos/quienesSomos.html',
        controller: 'QuienesSomosCtrl'
    }).when('/participa', {
        templateUrl: '/participa/participa.html',
        controller: 'ParticipaCtrl'
    }).otherwise({redirectTo: '/home'});

}]);

var app = angular.module('myApp');
app.run(['$rootScope', '$window',
    function($rootScope, $window) {

        $rootScope.user = {};

        $window.fbAsyncInit = function() {
            // Executed when the SDK is loaded

            FB.init({

                /*
                 The app id of the web app;
                 To register a new app visit Facebook App Dashboard
                 ( https://developers.facebook.com/apps/ )
                 */

                appId: '174931712664653',

                /*
                 Adding a Channel File improves the performance
                 of the javascript SDK, by addressing issues
                 with cross-domain communication in certain browsers.
                 */

                //channelUrl: 'app/channel.html',

                /*
                 Set if you want to check the authentication status
                 at the start up of the app
                 */

                status: true,

                /*
                 Enable cookies to allow the server to access
                 the session
                 */

                cookie: true,

                /* Parse XFBML */

                xfbml: true,

                version: 'v2.3'
            });

        };

        // Are you familiar to IIFE ( http://bit.ly/iifewdb ) ?

        (function(d){
            // load the Facebook javascript SDK

            var js,
                id = 'facebook-jssdk',
                ref = d.getElementsByTagName('script')[0];

            if (d.getElementById(id)) {
                return;
            }

            js = d.createElement('script');
            js.id = id;
            js.async = true;
            js.src = "//connect.facebook.net/es_LA/sdk.js";

            ref.parentNode.insertBefore(js, ref);

        }(document));

    }]);
<|endoftext|>


<commit_before>const express = require('express')
const csurf = require('csurf')
const path = require('path')
const routes = require('./routes')
const logger = require('./logger')
const setUpHealthChecks = require('./middleware/setUpHealthChecks')
const setUpAuthentication = require('./middleware/setUpAuthentication')
const populateCurrentUser = require('./middleware/populateCurrentUser')
const setUpWebRequestParsing = require('./middleware/setUpRequestParsing')
const setUpWebSecurity = require('./middleware/setUpWebSecurity')
const setUpWebSession = require('./middleware/setUpWebSession')
const setUpStaticResources = require('./middleware/setUpStaticResources')
const authorisationMiddleware = require('./middleware/authorisationMiddleware')
const rolesMiddleware = require('./middleware/rolesMiddleware')
const checkEtlInProgress = require('./middleware/check-etl-in-progress')
const nunjucksSetup = require('./utils/nunjucksSetup')

const auth = require('./authentication/auth')
const userService = require('./services/user-service')

const app = express()

app.set('json spaces', 2)
app.set('trust proxy', true)
app.set('port', process.env.PORT || 3000)

app.use(setUpHealthChecks())
app.use(setUpWebSecurity())
app.use(setUpWebSession())
app.use(setUpWebRequestParsing())
app.use(setUpStaticResources())
nunjucksSetup(app, path)
app.use(setUpAuthentication())
app.use(authorisationMiddleware(['ROLE_WORKLOAD_MEASUREMENT']))
app.use(rolesMiddleware())

// Log each HTML request and it's response.
app.use(function (req, res, next) {
  // Log response started.
  logger.info(req.method, req.path, 'called.')
  next()
})

// Check for valid CSRF tokens on state-changing methods.
app.use(csurf())

// Generate CSRF tokens to be sent in POST requests
app.use(function (req, res, next) {
  if (Object.prototype.hasOwnProperty.call(req, 'csrfToken')) {
    res.locals.csrfToken = req.csrfToken()
  }
  next()
})

// Build the router to route all HTTP requests and pass to the routes file for route configuration.
const router = express.Router({ mergeParams: true })
router.use(auth.authenticationMiddleware())
router.use(populateCurrentUser(userService))

app.use(checkEtlInProgress)

routes(router)

app.use('/', router)

// catch CSRF token errors
app.use(function (err, req, res, next) {
  const CSURF_ERROR_CODE = 'EBADCSRFTOKEN'
  if (err.code !== CSURF_ERROR_CODE) return next(err)
  res.status(403)
  res.render('includes/error', {
    error: 'Invalid CSRF token'
  })
})

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

app.use(function (err, req, res, next) {
  logger.error(err)
  res.status(err.status || 500)
  if (err.status === 404) {
    res.render('includes/error-404')
  } else {
    res.render('includes/error')
  }
})

module.exports = app
<commit_msg>added returning render for app js<commit_after>const express = require('express')
const csurf = require('csurf')
const path = require('path')
const routes = require('./routes')
const logger = require('./logger')
const setUpHealthChecks = require('./middleware/setUpHealthChecks')
const setUpAuthentication = require('./middleware/setUpAuthentication')
const populateCurrentUser = require('./middleware/populateCurrentUser')
const setUpWebRequestParsing = require('./middleware/setUpRequestParsing')
const setUpWebSecurity = require('./middleware/setUpWebSecurity')
const setUpWebSession = require('./middleware/setUpWebSession')
const setUpStaticResources = require('./middleware/setUpStaticResources')
const authorisationMiddleware = require('./middleware/authorisationMiddleware')
const rolesMiddleware = require('./middleware/rolesMiddleware')
const checkEtlInProgress = require('./middleware/check-etl-in-progress')
const nunjucksSetup = require('./utils/nunjucksSetup')

const auth = require('./authentication/auth')
const userService = require('./services/user-service')

const app = express()

app.set('json spaces', 2)
app.set('trust proxy', true)
app.set('port', process.env.PORT || 3000)

app.use(setUpHealthChecks())
app.use(setUpWebSecurity())
app.use(setUpWebSession())
app.use(setUpWebRequestParsing())
app.use(setUpStaticResources())
nunjucksSetup(app, path)
app.use(setUpAuthentication())
app.use(authorisationMiddleware(['ROLE_WORKLOAD_MEASUREMENT']))
app.use(rolesMiddleware())

// Log each HTML request and it's response.
app.use(function (req, res, next) {
  // Log response started.
  logger.info(req.method, req.path, 'called.')
  next()
})

// Check for valid CSRF tokens on state-changing methods.
app.use(csurf())

// Generate CSRF tokens to be sent in POST requests
app.use(function (req, res, next) {
  if (Object.prototype.hasOwnProperty.call(req, 'csrfToken')) {
    res.locals.csrfToken = req.csrfToken()
  }
  next()
})

// Build the router to route all HTTP requests and pass to the routes file for route configuration.
const router = express.Router({ mergeParams: true })
router.use(auth.authenticationMiddleware())
router.use(populateCurrentUser(userService))

app.use(checkEtlInProgress)

routes(router)

app.use('/', router)

// catch CSRF token errors
app.use(function (err, req, res, next) {
  const CSURF_ERROR_CODE = 'EBADCSRFTOKEN'
  if (err.code !== CSURF_ERROR_CODE) return next(err)
  res.status(403)
  return res.render('includes/error', {
    error: 'Invalid CSRF token'
  })
})

app.use(function (req, res) {
  res.status(404)
  return res.render('includes/error-404')
})

app.use(function (err, req, res, next) {
  logger.error(err)
  if (res.headersSent) {
    return next(err)
  }
  res.status(err.status || 500)
  if (err.status === 404) {
    return res.render('includes/error-404')
  }
  return res.render('includes/error')
})

module.exports = app
<|endoftext|>


<commit_before>var credentials = require('./data/credential.json');
var ddb = require('dynamodb').ddb({ accessKeyId: credentials.accessKeyId,
                                    secretAccessKey: credentials.secretAccessKey,
                                    endpoint: 'dynamodb.us-west-2.amazonaws.com'});
var express = require('express');
var reload = require('reload');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

app.set('port', process.env.PORT || 80);
app.set('ddbsetup', ddb);//push ddb lib with router
app.set('view engine', 'ejs');//set up view engine for views behind router
app.set('views', 'app/views');//set up view engine folder

app.locals.siteTitle = 'FoodDeliverSystem';//set up public varible
//routes start here
app.use(express.static('app/public'));//set up middleware for folder public
app.use(require('./routes/index'));// home page
app.use(require('./routes/packageinfo'));//dynamodb query, dynamodb query/:index, dunamodb query last
app.use(require('./routes/dynamodbapi'));//dynamo db API for put, post, delete. See dynamodbapi.js for details
app.use(require('./routes/login'));//test login page
app.use(require('./routes/apiform'));//API samples with forms
app.use(require('./routes/searchpage'));//search page for latest scan info

// start the server
var server = app.listen(app.get('port'), function() {
    console.log('Listening on port: ' + app.get('port'));
});

reload(server, app);<commit_msg>port on 3000<commit_after>var credentials = require('./data/credential.json');
var ddb = require('dynamodb').ddb({ accessKeyId: credentials.accessKeyId,
                                    secretAccessKey: credentials.secretAccessKey,
                                    endpoint: 'dynamodb.us-west-2.amazonaws.com'});
var express = require('express');
var reload = require('reload');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

app.set('port', process.env.PORT || 3000);
app.set('ddbsetup', ddb);//push ddb lib with router
app.set('view engine', 'ejs');//set up view engine for views behind router
app.set('views', 'app/views');//set up view engine folder

app.locals.siteTitle = 'FoodDeliverSystem';//set up public varible
//routes start here
app.use(express.static('app/public'));//set up middleware for folder public
app.use(require('./routes/index'));// home page
app.use(require('./routes/packageinfo'));//dynamodb query, dynamodb query/:index, dunamodb query last
app.use(require('./routes/dynamodbapi'));//dynamo db API for put, post, delete. See dynamodbapi.js for details
app.use(require('./routes/login'));//test login page
app.use(require('./routes/apiform'));//API samples with forms
app.use(require('./routes/searchpage'));//search page for latest scan info

// start the server
var server = app.listen(app.get('port'), function() {
    console.log('Listening on port: ' + app.get('port'));
});

reload(server, app);<|endoftext|>


<commit_before>import Ember from 'ember';
import Resolver from './resolver';
import "npm:babel-polyfill";
import loadInitializers from 'ember-load-initializers';
import config from './config/environment';

/* global L */

let App;

L.Icon.Default.imagePath = 'http://ember-prototype.s3-website-us-east-1.amazonaws.com/assets/images';

Ember.MODEL_FACTORY_INJECTIONS = true;

App = Ember.Application.extend({
  rootElement: '#ember-app',
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver
});

loadInitializers(App, config.modulePrefix);

export default App;

Ember.onerror = function (error) {
  // console.log('GLOBAL ERROR:', error.message);
  console.log(error.stack);
  if(error.message.toLowerCase().indexOf("uri")>-1) {
    window.location = `/explore/error/${error.message}`;
  }
	//TODO: Quick and dirty redirect...
	//This will route to, in any case, to either a 404 or error page
	//and will nicely deposit the user back to the explore index.
	//as long as the root is /explore.
  //TODO: Need to figure out how to transition to route from here.
  //TODO: One possible solution is to catch the error in the router
  //and modify the target route.
};
<commit_msg>Monkeypatch Ember.assign<commit_after>import Ember from 'ember';
import Resolver from './resolver';
import "npm:babel-polyfill";
import loadInitializers from 'ember-load-initializers';
import config from './config/environment';
Ember.assign = Object.assign;

/* global L */

let App;

L.Icon.Default.imagePath = 'http://ember-prototype.s3-website-us-east-1.amazonaws.com/assets/images';

Ember.MODEL_FACTORY_INJECTIONS = true;

App = Ember.Application.extend({
  rootElement: '#ember-app',
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver
});

loadInitializers(App, config.modulePrefix);

export default App;

Ember.onerror = function (error) {
  // console.log('GLOBAL ERROR:', error.message);
  console.log(error.stack);
  if(error.message.toLowerCase().indexOf("uri")>-1) {
    window.location = `/explore/error/${error.message}`;
  }
	//TODO: Quick and dirty redirect...
	//This will route to, in any case, to either a 404 or error page
	//and will nicely deposit the user back to the explore index.
	//as long as the root is /explore.
  //TODO: Need to figure out how to transition to route from here.
  //TODO: One possible solution is to catch the error in the router
  //and modify the target route.
};
<|endoftext|>


<commit_before>(function () {
    'use strict';

// Declare app level module which depends on views, and components
    angular.module('app', [
        "oc.lazyLoad",
        'ngRoute',
        'ngAnimate',
        'angular-storage',
        'angular-jwt',
        'auth0',
        'acUtils',
        'acSucursales',
        'acAutocomplete',
        'acUsuarios',
        'acUsuariosAdministracion',
        'acProductos',
        'acProductosAdministracion',
        'acStocks',
        'acPagoProveedores',
        'acPedidosAdministracion',
        'acPedidosDetalles',
        'acReportes',
        'acContacts',
        'acMovimientos',
        'acCajas',
        'acCobros',
        'acGastos',
        'acDepositos',
        'acResumenCajaDiaria',
        'acAbrirCerrarCaja',
        'LangTables',
        'acUploads'
    ]).config(['$routeProvider', 'authProvider', function ($routeProvider, authProvider) {
            authProvider.init({
                domain: 'ac-desarrollos.auth0.com',
                clientID: 'su5JUmdUk52EWhfK5xxZJtnw6W3IK9c1',
                loginUrl: '/ingreso'
            });

            $routeProvider.when('/login', {
                templateUrl: 'login/login.html',
                controller: 'LoginController',
                data: {requiresLogin: false},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('login/login.js');
                    }]
                }
            });

            $routeProvider.when('/main', {
                templateUrl: 'main/main.html',
                controller: 'MainController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('main/main.js');
                    }]
                }
            });

            $routeProvider.when('/administracion/productos', {
                templateUrl: 'productos/productos.html',
                controller: 'ProductosController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('productos/productos.js');
                    }]
                }
            });

            $routeProvider.when('/administracion/usuarios', {
                templateUrl: 'usuarios/usuarios.html',
                controller: 'UsuariosController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('usuarios/usuarios.js');
                    }]
                }
            });

            $routeProvider.when('/caja/cobros', {
                templateUrl: 'cobros/cobros.html',
                controller: 'CobrosController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('cobros/cobros.js');
                    }]
                }
            });

            $routeProvider.when('/caja/abrir_cerrar_caja', {
                templateUrl: 'abrir-cerrar-caja/abrir-cerrar-caja.html',
                controller: 'AbrirCerrarCajasController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('abrir-cerrar-caja/abrir-cerrar-caja.js');
                    }]
                }
            });

            $routeProvider.when('/caja/gastos', {
                templateUrl: 'gastos/gastos.html',
                controller: 'GastosController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('gastos/gastos.js');
                    }]
                }
            });

            $routeProvider.when('/caja/depositos', {
                templateUrl: 'depositos/depositos.html',
                controller: 'DepositosController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('depositos/depositos.js');
                    }]
                }
            });

            $routeProvider.when('/stock/pedidos', {
                templateUrl: 'pedidos/pedidos.html',
                controller: 'PedidosController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('pedidos/pedidos.js');
                    }]
                }
            });

            $routeProvider.when('/stock/confirmar', {
                templateUrl: 'confirmar/confirmar.html',
                controller: 'ConfirmarController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('confirmar/confirmar.js');
                    }]
                }
            });
        }])
        .controller('AppCtrl', AppCtrl);

    AppCtrl.$inject = ['UserService', '$location', '$rootScope','$interval'];
    function AppCtrl(UserService, $location, $rootScope, $interval) {
        var vm = this;
        vm.isLogged = false;
        vm.user = undefined;
        vm.time = new Date().format('dddd, mmmm d, yyyy h:MM TT');

        $interval(function(){

            vm.time = new Date().format('dddd, mmmm d, yyyy h:MM TT');
        }, 6000);

        vm.menu = $location.path().split('/')[1];

        if (!UserService.getFromToken()) {
            $location.path('/login')
        } else {
            vm.user = UserService.getFromToken();
        }

        $rootScope.$on('login-success', function () {
            vm.user = UserService.getFromToken();
            //SucursalesService.getByParams('sucursal_id', 'nombre', 'true')
        });

        $rootScope.$on('login-error', function () {
            vm.user = undefined;
        });

    }

})();
<commit_msg>Ariel<commit_after>(function () {
    'use strict';

// Declare app level module which depends on views, and components
    angular.module('app', [
        "oc.lazyLoad",
        'ngRoute',
        'ngAnimate',
        'angular-storage',
        'angular-jwt',
        'auth0',
        'acUtils',
        'acSucursales',
        'acAutocomplete',
        'acUsuarios',
        'acUsuariosAdministracion',
        'acProductos',
        'acProductosAdministracion',
        'acStocks',
        'acPagoProveedores',
        'acPedidosAdministracion',
        'acPedidosDetalles',
        'acReportes',
        'acContacts',
        'acMovimientos',
        'acCajas',
        'acCobros',
        'acGastos',
        'acDepositos',
        'acResumenCajaDiaria',
        'acAbrirCerrarCaja',
        'LangTables',
        'acUploads'
    ]).config(['$routeProvider', 'authProvider', function ($routeProvider, authProvider) {
            authProvider.init({
                domain: 'ac-desarrollos.auth0.com',
                clientID: 'su5JUmdUk52EWhfK5xxZJtnw6W3IK9c1',
                loginUrl: '/ingreso'
            });

            $routeProvider.when('/login', {
                templateUrl: 'login/login.html',
                controller: 'LoginController',
                data: {requiresLogin: false},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('login/login.js');
                    }]
                }
            });

            $routeProvider.when('/main', {
                templateUrl: 'main/main.html',
                controller: 'MainController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('main/main.js');
                    }]
                }
            });

            $routeProvider.when('/administracion/productos', {
                templateUrl: 'productos/productos.html',
                controller: 'ProductosController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('productos/productos.js');
                    }]
                }
            });

            $routeProvider.when('/administracion/usuarios', {
                templateUrl: 'usuarios/usuarios.html',
                controller: 'UsuariosController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('usuarios/usuarios.js');
                    }]
                }
            });

            $routeProvider.when('/caja/cobros', {
                templateUrl: 'cobros/cobros.html',
                controller: 'CobrosController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('cobros/cobros.js');
                    }]
                }
            });

            $routeProvider.when('/caja/abrir_cerrar_caja', {
                templateUrl: 'abrir-cerrar-caja/abrir-cerrar-caja.html',
                controller: 'AbrirCerrarCajasController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('abrir-cerrar-caja/abrir-cerrar-caja.js');
                    }]
                }
            });

            $routeProvider.when('/caja/gastos', {
                templateUrl: 'gastos/gastos.html',
                controller: 'GastosController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('gastos/gastos.js');
                    }]
                }
            });

            $routeProvider.when('/caja/depositos', {
                templateUrl: 'depositos/depositos.html',
                controller: 'DepositosController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('depositos/depositos.js');
                    }]
                }
            });

            $routeProvider.when('/stock/pedidos', {
                templateUrl: 'pedidos/pedidos.html',
                controller: 'PedidosController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('pedidos/pedidos.js');
                    }]
                }
            });

            $routeProvider.when('/stock/confirmar', {
                templateUrl: 'confirmar/confirmar.html',
                controller: 'ConfirmarController',
                data: {requiresLogin: true},
                resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
                    loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                        // you can lazy load files for an existing module
                        return $ocLazyLoad.load('confirmar/confirmar.js');
                    }]
                }
            });
        }])
        .controller('AppCtrl', AppCtrl);

    AppCtrl.$inject = ['UserService', '$location', '$rootScope','$interval', 'ProductService', 'StockService'];
    function AppCtrl(UserService, $location, $rootScope, $interval, ProductService, StockService) {
        var vm = this;
        vm.isLogged = false;
        vm.user = undefined;
        vm.time = new Date().format('dddd, mmmm d, yyyy h:MM TT');

        ProductService.get();
        StockService.get();

        $interval(function(){

            vm.time = new Date().format('dddd, mmmm d, yyyy h:MM TT');
        }, 6000);

        vm.menu = $location.path().split('/')[1];

        if (!UserService.getFromToken()) {
            $location.path('/login')
        } else {
            vm.user = UserService.getFromToken();
        }

        $rootScope.$on('login-success', function () {
            vm.user = UserService.getFromToken();
            //SucursalesService.getByParams('sucursal_id', 'nombre', 'true')
        });

        $rootScope.$on('login-error', function () {
            vm.user = undefined;
        });

    }

})();
<|endoftext|>


<commit_before>var app = require('app'),
  BrowserWindow = require('browser-window'),
  ipc = require('ipc'),
  Menu = require('menu'),
  dialog = require('dialog'),
  config = {},
  fs = require('fs')
  path = require('path');

// report crashes to atom-shell
require('crash-reporter').start();

//------------------------------------------------------------------------------
// Dialogs
// (These have to be created on the "browser" side, i.e. here, not on the "page")
//------------------------------------------------------------------------------

const addProjectDialogOptions = {
  title: "Select an existing project (project.clj)",
  properties: ["openFile"],
  filters: [
    {
      name: "Leiningen project config",
       extensions: ["clj"]
    }
  ]
};

function showAddExistingProjectDialog() {
  dialog.showOpenDialog(addProjectDialogOptions, function(filenames) {
    if (filenames) {
      var filename = filenames[0];
      mainWindow.webContents.send("add-existing-project-dialog-success", filename);
    }
  });
}

ipc.on("request-add-existing-project-dialog", showAddExistingProjectDialog);

//------------------------------------------------------------------------------
// Menu Builder
//------------------------------------------------------------------------------

const menuTemplate = [
  {
    label: "File", // NOTE: On Mac, the first menu item is always the name of the Application
                   //       (uses CFBundleName in Info.plist, set by "release.sh")
    submenu: [
      {
        label: "Add Existing Project",
        click: showAddExistingProjectDialog
      }
    ]
  }
];

var menu = Menu.buildFromTemplate(menuTemplate);

// FIXME: custom menu disabled, since CMD+Q doesn't work without the menu item for it
// Menu.setApplicationMenu(menu);

//------------------------------------------------------------------------------
// Main
//------------------------------------------------------------------------------

// load config
// NOTE: this is mostly for development purposes
if (fs.existsSync(__dirname + '/config.json')) {
  config = require(__dirname + '/config.json');
}

// load window information
const windowInformationFile = app.getDataPath() + path.sep + 'window.json';
var windowInformation = {};
if (fs.existsSync(windowInformationFile)) {
  windowInformation = require(windowInformationFile);
}

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;

var bounceID;

function onStartBounce() {
  // run bounce and set to bounceID
  bounceID = app.dock.bounce("critical");
  console.log(bounceID);

  // test code to see how setBadge works
  app.dock.setBadge("E");
}

// ipc.on('start-bounce', onStartBounce);

function onStopBounce() {
  // need to get bounceID as returned from app.dock.bounce() and pass to
  // app.dock.cancelBounce(id)
  app.dock.cancelBounce(0);
}

// ipc.on('stop-bounce', onStopBounce);

function shutdownForReal() {
  // save current window information
  windowInformation.maximized = mainWindow.isMaximized();
  windowInformation.position = mainWindow.getPosition();
  windowInformation.size = mainWindow.getSize();
  fs.writeFileSync(windowInformationFile, JSON.stringify(windowInformation));

  // NOTE: so the docs say to only use this when the page has crashed, but I think
  // it's ok in this case because of the way we're "trapping" the regular close event
  // https://github.com/atom/atom-shell/blob/master/docs/api/browser-window.md#browserwindowdestroy
  // TODO: look into using app.quit() here instead
  mainWindow.destroy();
}

ipc.on('shutdown-for-real', shutdownForReal);

// NOTE: copied this directly from the atom-shell docs
// is this really necessary?
function onWindowClosed() {
  // dereference the window object
  mainWindow = null;
}

function onWindowClose(evt) {
  // prevent window close
  evt.preventDefault();

  // send shutdown signal to the window
  mainWindow.webContents.send('shutdown');
}

// send the OS-normalized app data path to the webpage
// NOTE: this event triggers the "global app init" on the webpage side
function onFinishLoad() {
  mainWindow.webContents.send('config-file-location', app.getDataPath());
}

// NOTE: not all of the browserWindow options listed on the docs page work
// on all operating systems
const browserWindowOptions = {
  height: 850,
  icon: __dirname + '/img/clojure-logo.png',
  title: 'ClojureScript Compiler',
  width: 1000
};

function startApp() {
  // create the browser window
  mainWindow = new BrowserWindow(browserWindowOptions);

  // load index.html
  mainWindow.loadUrl('file://' + __dirname + '/index.html');

  // send info to the webpage
  mainWindow.webContents.on('did-finish-load', onFinishLoad);

  // Emitted when the user tries to close the window
  mainWindow.on('close', onWindowClose);

  // Emitted when the window is closed.
  mainWindow.on('closed', onWindowClosed);

  // optionally launch dev tools
  if (config.hasOwnProperty("dev-tools") && config["dev-tools"] === true) {
    mainWindow.openDevTools();
  }

  // position window initially
  if (windowInformation.hasOwnProperty('maximized') &&
      windowInformation.maximized === true) {
    mainWindow.maximize();
  }
  else if (windowInformation.hasOwnProperty('size') &&
           windowInformation.hasOwnProperty('position')) {
    mainWindow.setPosition(windowInformation.position[0], windowInformation.position[1]);
    mainWindow.setSize(windowInformation.size[0], windowInformation.size[1]);
  }
}

// This method will be called when atom-shell has done everything
// initialization and ready for creating browser windows.
app.on('ready', startApp);
<commit_msg>minor<commit_after>var app = require('app'),
  BrowserWindow = require('browser-window'),
  dialog = require('dialog'),
  fs = require('fs')
  ipc = require('ipc'),
  Menu = require('menu'),
  path = require('path');

// report crashes to atom-shell
require('crash-reporter').start();

//------------------------------------------------------------------------------
// Dialogs
// (These have to be created on the "browser" side, i.e. here, not on the "page")
//------------------------------------------------------------------------------

const addProjectDialogOptions = {
  title: "Select an existing project (project.clj)",
  properties: ["openFile"],
  filters: [
    {
      name: "Leiningen project config",
       extensions: ["clj"]
    }
  ]
};

function showAddExistingProjectDialog() {
  dialog.showOpenDialog(addProjectDialogOptions, function(filenames) {
    if (filenames) {
      var filename = filenames[0];
      mainWindow.webContents.send("add-existing-project-dialog-success", filename);
    }
  });
}

ipc.on("request-add-existing-project-dialog", showAddExistingProjectDialog);

//------------------------------------------------------------------------------
// Menu Builder
//------------------------------------------------------------------------------

const menuTemplate = [
  {
    label: 'File', // NOTE: On Mac, the first menu item is always the name of the Application
                   //       (uses CFBundleName in Info.plist, set by "release.sh")
    submenu: [
      {
        label: 'Add Existing Project',
        click: showAddExistingProjectDialog
      }
    ]
  }
];

var menu = Menu.buildFromTemplate(menuTemplate);

// FIXME: custom menu disabled, since CMD+Q doesn't work without the menu item for it
// Menu.setApplicationMenu(menu);

//------------------------------------------------------------------------------
// Main
//------------------------------------------------------------------------------

// load development config (optional)
var devConfig = {};
if (fs.existsSync(__dirname + '/config.json')) {
  devConfig = require(__dirname + '/config.json');
}

// load window information
const windowInformationFile = app.getDataPath() + path.sep + 'window.json';
var windowInformation = {};
if (fs.existsSync(windowInformationFile)) {
  windowInformation = require(windowInformationFile);
}

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// dock bounce on Mac (disabled for now)

var bounceID;

function onStartBounce() {
  // run bounce and set to bounceID
  bounceID = app.dock.bounce("critical");
  console.log(bounceID);

  // test code to see how setBadge works
  app.dock.setBadge("E");
}

ipc.on('start-bounce', onStartBounce);

function onStopBounce() {
  // need to get bounceID as returned from app.dock.bounce() and pass to
  // app.dock.cancelBounce(id)
  app.dock.cancelBounce(0);
}

ipc.on('stop-bounce', onStopBounce);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

function shutdownForReal() {
  // save current window information
  windowInformation.maximized = mainWindow.isMaximized();
  windowInformation.position = mainWindow.getPosition();
  windowInformation.size = mainWindow.getSize();
  fs.writeFileSync(windowInformationFile, JSON.stringify(windowInformation));

  // NOTE: so the docs say to only use this when the page has crashed, but I think
  // it's ok in this case because of the way we're "trapping" the regular close event
  // https://github.com/atom/atom-shell/blob/master/docs/api/browser-window.md#browserwindowdestroy
  // TODO: look into using app.quit() here instead
  mainWindow.destroy();
}

ipc.on('shutdown-for-real', shutdownForReal);

// NOTE: copied this directly from the atom-shell docs
// is this really necessary?
function onWindowClosed() {
  // dereference the window object
  mainWindow = null;
}

function onWindowClose(evt) {
  // prevent window close
  evt.preventDefault();

  // send shutdown signal to the window
  mainWindow.webContents.send('shutdown');
}

// send the OS-normalized app data path to the webpage
// NOTE: this event triggers the "global app init" on the webpage side
function onFinishLoad() {
  mainWindow.webContents.send('config-file-location', app.getDataPath());
}

// NOTE: not all of the browserWindow options listed on the docs page work
// on all operating systems
const browserWindowOptions = {
  height: 850,
  icon: __dirname + '/img/clojure-logo.png',
  title: 'ClojureScript Compiler',
  width: 1000
};

function startApp() {
  // create the browser window
  mainWindow = new BrowserWindow(browserWindowOptions);

  // load index.html
  mainWindow.loadUrl('file://' + __dirname + '/index.html');

  // send info to the webpage
  mainWindow.webContents.on('did-finish-load', onFinishLoad);

  // Emitted when the user tries to close the window
  mainWindow.on('close', onWindowClose);

  // Emitted when the window is closed.
  mainWindow.on('closed', onWindowClosed);

  // optionally launch dev tools
  if (devConfig.hasOwnProperty('dev-tools') &&
      devConfig['dev-tools'] === true) {
    mainWindow.openDevTools();
  }

  // position window initially
  if (windowInformation.hasOwnProperty('maximized') &&
      windowInformation.maximized === true) {
    mainWindow.maximize();
  }
  else if (windowInformation.hasOwnProperty('size') &&
           windowInformation.hasOwnProperty('position')) {
    mainWindow.setPosition(windowInformation.position[0], windowInformation.position[1]);
    mainWindow.setSize(windowInformation.size[0], windowInformation.size[1]);
  }
}

// This method will be called when atom-shell has done everything
// initialization and ready for creating browser windows.
app.on('ready', startApp);
<|endoftext|>