<commit_before>'use strict';

// nitty gritty //
var express = require('express');
var braintree = require('braintree');
var router = express.Router(); // eslint-disable-line new-cap
var gateway = require('../lib/gateway');

var TRANSACTION_SUCCESS_STATUSES = [
  braintree.Transaction.Status.Authorizing,
  braintree.Transaction.Status.Authorized,
  braintree.Transaction.Status.Settled,
  braintree.Transaction.Status.Settling,
  braintree.Transaction.Status.SettlementConfirmed,
  braintree.Transaction.Status.SettlementPending,
  braintree.Transaction.Status.SubmittedForSettlement
];

function formatErrors(errors) {
  var formattedErrors = '';

  for (var i in errors) { // eslint-disable-line no-inner-declarations, vars-on-top
    if (errors.hasOwnProperty(i)) {
      formattedErrors += 'Error: ' + errors[i].code + ': ' + errors[i].message + '\n';
    }
  }
  return formattedErrors;
}

function createResultObject(transaction) {
  var result;
  var status = transaction.status;

  if (TRANSACTION_SUCCESS_STATUSES.indexOf(status) !== -1) {
    result = {
      header: 'Sweet Success!',
      icon: 'success',
      message: 'Your test transaction has been successfully processed. See the Braintree API response and try again.'
    };
  } else {
    result = {
      header: 'Transaction Failed',
      icon: 'fail',
      message: 'Your test transaction has a status of ' + status + '. See the Braintree API response and try again.'
    };
  }

  return result;
}

router.get('/', function (req, res) {
  res.redirect('/checkouts/new');
});

router.get('/checkouts/new', function (req, res) {
  gateway.clientToken.generate({}, function (err, response) {
    res.render('checkouts/new', {clientToken: response.clientToken, messages: req.flash('error')});
  });
});

router.get('/checkouts/:id', function (req, res) {
  var result;
  var transactionId = req.params.id;

  gateway.transaction.find(transactionId, function (err, transaction) {
    result = createResultObject(transaction);
    res.render('checkouts/show', {transaction: transaction, result: result});
  });
});

router.post('/checkouts', function (req, res) {
  var transactionErrors;
  var amount = req.body.amount; // In production you should not take amounts directly from clients
  var nonce = req.body.payment_method_nonce;
  var cardholderName = req.body.cardholderName;
  var startDate = new Date(Date.UTC(2016, 8, 6, 0, 0, 0));

  gateway.customer.create({
  paymentMethodNonce: nonce,
  firstName: "Cecilia",
  lastName: "Ramirez",
  customFields: {
    initialcourse: "Introduction to Scratch",
    childage: "8",
    childlastname: "Ramirez",
    childfirstname: "Isabella"
  }
  }, function (err, result) {
    if (result.success) {
      var token = result.customer.paymentMethods[0].token;
        gateway.subscription.create({
          paymentMethodToken: token,
          planId: "four_month_membership_id",
          firstBillingDate: startDate
        }, function (err, result) {
          result.success;
        });
       res.redirect('/');
    } else {
      transactionErrors = result.errors.deepErrors();
      req.flash('error', {msg: formatErrors(transactionErrors)});
      res.redirect('checkouts/new');
    }
  });

  // gateway.transaction.sale({
  //   amount: amount,
  //   paymentMethodNonce: nonce
  // }, function (err, result) {
  //   if (result.success || result.transaction) {
  //     res.redirect('checkouts/' + result.transaction.id);
  //   } else {
  //     transactionErrors = result.errors.deepErrors();
  //     req.flash('error', {msg: formatErrors(transactionErrors)});
  //     res.redirect('checkouts/new');
  //   }
  // });
});

module.exports = router;
<commit_msg>Update index.js<commit_after>'use strict';

// nitty gritty //
var express = require('express');
var braintree = require('braintree');
var router = express.Router(); // eslint-disable-line new-cap
var gateway = require('../lib/gateway');

var TRANSACTION_SUCCESS_STATUSES = [
  braintree.Transaction.Status.Authorizing,
  braintree.Transaction.Status.Authorized,
  braintree.Transaction.Status.Settled,
  braintree.Transaction.Status.Settling,
  braintree.Transaction.Status.SettlementConfirmed,
  braintree.Transaction.Status.SettlementPending,
  braintree.Transaction.Status.SubmittedForSettlement
];

function formatErrors(errors) {
  var formattedErrors = '';

  for (var i in errors) { // eslint-disable-line no-inner-declarations, vars-on-top
    if (errors.hasOwnProperty(i)) {
      formattedErrors += 'Error: ' + errors[i].code + ': ' + errors[i].message + '\n';
    }
  }
  return formattedErrors;
}

function createResultObject(transaction) {
  var result;
  var status = transaction.status;

  if (TRANSACTION_SUCCESS_STATUSES.indexOf(status) !== -1) {
    result = {
      header: 'Sweet Success!',
      icon: 'success',
      message: 'Your test transaction has been successfully processed. See the Braintree API response and try again.'
    };
  } else {
    result = {
      header: 'Transaction Failed',
      icon: 'fail',
      message: 'Your test transaction has a status of ' + status + '. See the Braintree API response and try again.'
    };
  }

  return result;
}

router.get('/', function (req, res) {
  res.redirect('/checkouts/new');
});

router.get('/checkouts/new', function (req, res) {
  gateway.clientToken.generate({}, function (err, response) {
    res.render('checkouts/new', {clientToken: response.clientToken, messages: req.flash('error')});
  });
});

router.get('/checkouts/:id', function (req, res) {
  var result;
  var transactionId = req.params.id;

  gateway.transaction.find(transactionId, function (err, transaction) {
    result = createResultObject(transaction);
    res.render('checkouts/show', {transaction: transaction, result: result});
  });
});

router.post('/checkouts', function (req, res) {
  var transactionErrors;
  var amount = req.body.amount; // In production you should not take amounts directly from clients
  var nonce = req.body.payment_method_nonce;
  var cardholderName = req.body.cardholderName;
  var startDate = new Date(Date.UTC(2016, 8, 6, 0, 0, 0));

  // gateway.customer.create({
  // paymentMethodNonce: nonce,
  // firstName: "Cecilia",
  // lastName: "Ramirez",
  // customFields: {
  //   initialcourse: "Introduction to Scratch",
  //   childage: "8",
  //   childlastname: "Ramirez",
  //   childfirstname: "Isabella"
  // }
  // }, function (err, result) {
  //   if (result.success) {
  //     var token = result.customer.paymentMethods[0].token;
  //       gateway.subscription.create({
  //         paymentMethodToken: token,
  //         planId: "four_month_membership_id",
  //         firstBillingDate: startDate
  //       }, function (err, result) {
  //         result.success;
  //       });
  //     res.redirect('/');
  //   } else {
  //     res.redirect('/');
  //   }
  // });

  gateway.transaction.sale({
    amount: amount,
    paymentMethodNonce: nonce
  }, function (err, result) {
    if (result.success || result.transaction) {
      res.redirect('checkouts/' + result.transaction.id);
    } else {
      transactionErrors = result.errors.deepErrors();
      req.flash('error', {msg: formatErrors(transactionErrors)});
      res.redirect('checkouts/new');
    }
  });
});

module.exports = router;
<|endoftext|>


<commit_before>
/*
 * GET home page.
 */

exports.index = function(req, res){
  res.render('index', { title: 'Express' });
};<commit_msg>Welcome to caracol. It's a small c.<commit_after>
/*
 * GET home page.
 */

exports.index = function(req, res){
  res.render('index', { title: 'caracol' });
};<|endoftext|>


<commit_before>var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('pluses.db');
var express = require('express');
var router = express.Router();
var request = require('request');
var http = require('http');
var querystring = require('querystring');
var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
var image_index = 0;
var rando = false;

router.post('/', function(req, res) {
	// Replace spaces in request
	var term = req.body.text.replace(/^\./g, ''),
        parts = term.split(" "),
        command = parts[0],
        args = parts.slice(1).join(" "),
		finishCall = function(item) {
			res.end(JSON.stringify({text: item}));
		};
    if (parts[1]) {
        var nick = parts[1],
            nick = nick.replace(/[^a-zA-z0-9_ \.-]/g, '');
    }
    var leaderboard = function (table) {
        db.all("SELECT nick, pluses FROM " + table + " ORDER BY pluses DESC LIMIT 10", function (err, rows) {
            var leaders = table.charAt(0).toUpperCase() + table.slice(1) + " Leaderboard:\n";
            var i = 0;
            rows.forEach(function (row) {
                i++;
                leaders += i + ". " + row.pluses + " " + row.nick + "\n";
            });
            finishCall(leaders);
        });
    }

    var add_one = function(table, nick, req) {
        if (nick != req.body.user_name) {
            console.log("|" + nick + "| incremented " + table);
            db.run("INSERT OR IGNORE INTO " + table + " VALUES (?, 0)", nick);
            db.run("UPDATE " + table + " SET pluses = pluses + 1 WHERE nick = ?", nick);

            db.get("SELECT pluses FROM " + table + " WHERE nick = ?", nick, function (err, row) {
                finishCall(nick + " now has " + row.pluses + " " + table);
            });
        } else {
            finishCall("nice try");
        }
    }

    var sub_one = function(table, nick, req) {
        console.log("|" + req.body.user_name + "| tried to decrement" + table);
        db.run("INSERT OR IGNORE INTO " + table + " VALUES (?, 0)", req.body.user_name);
        db.run("UPDATE " + table + " SET pluses = pluses - 1 WHERE nick = ?", req.body.user_name);

        db.get("SELECT pluses FROM " + table + " WHERE nick = ?", req.body.user_name, function (err, row) {
            finishCall("Don't be a meanie! " + req.body.user_name + " now has " + row.pluses + " " + table);
        });
    }

    var learn = function(nick, command, response) {
        db.run("INSERT OR IGNORE INTO commands VALUES (?, ?, ?)", nick, command, response);
        finishCall("Learned command: " + command);
    }

    var respond = function(nick, command) {
        db.get("SELECT response FROM commands WHERE command = ? ORDER BY RANDOM() LIMIT 1", command, function (err, row) {
            finishCall(row.response);
        });
    }

    switch (command) {
        case "increment":
        case "pluses":
        case "plus":
            if (!nick) {
                leaderboard("pluses");
            } else {
                add_one("pluses", nick, req);
            }
            break;
        case "decrement":
            sub_one("pluses", nick, req);
            break;
        case "troll":
        case "trolls":
            if (!nick) {
                leaderboard("trolls");
            } else {
                add_one("trolls", nick);
            }
            break;
        case "resummon":
            rando = true;
        case "summon":
        case "gif":
            if (0 && req.body.user_name == "travis") {
                finishCall("http://4.bp.blogspot.com/_Nu9qz3BZvZU/S427XIB031I/AAAAAAAAAPg/38S5euCch7k/s400/justin_bieber_wallpaper_album_2009.jpg");
                break;
            }
            var options = {
                host: 'www.google.com',
                port: 80,
                path: "/search?safe=strict&tbm=isch&q=" + encodeURIComponent(args),
                method: 'GET',
                headers: {
                    'user-agent': 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
                }
            };
            var tmpist = [];
            var req = http.get(options,
                function(res) {
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        tmpist.push(chunk);
                    });

                    res.on('end', function (e) {
                        chunk = tmpist.join('');

                        var matches = chunk.match(/imgurl=(.*?)&/g);
                        if (matches) {
                            if (rando) {
                                image_index = Math.floor(Math.random() * matches.length);
                            }
                            var match = matches[image_index];
                            console.log(match);
                            rando = false;
                            finishCall(match.replace(/^imgurl=/, '').replace(/&$/, ''));
                        }
                    });
                }
            ).on("error", function (e) {
                finishCall("Got error: " + e.message);
            });

            break;
        case 'g':
        case 'google':
            var tmp = []
            var options = {
                host: 'ajax.googleapis.com',
                port: 80,
                path: '/ajax/services/search/web?v=1.0&rsz=large&start=0&q=' + encodeURIComponent(args),
                method: 'GET',
                headers: {
                    'user-agent': 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
                }
            };
            var req = http.request(options,
                function(res) {
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        tmp.push(chunk);
                    });

                    res.on('end', function (e) {
                        var body = tmp.join('');
                        var result = JSON.parse(body);
                        finishCall(
                            result.responseData.results[0].titleNoFormatting + " @ " +
                            result.responseData.results[0].unescapedUrl
                        );
                    });
                }
            ).on("error", function (e) {
                finishCall("Got error: " + e.message);
            });
            req.end();
            break;
        case 'source':
            finishCall('https://github.com/jayson/SlackCat');
            break;
        case 'gitup':
            exec("git pull", function (error, stdout, stderr) {
                finishCall(stdout + "\n" + stderr);
            });
            break;
        case 'youtube':
            exec("./youtube.py " + args, function (error, stdout, stderr) {
                finishCall(stdout + "\n" + stderr);
            });
            break;
        case 'q':
        case 'quote':
            var symbol = args.replace(/\./, '-');
            var params = [
                's',
                'k1',
                'k2',
                'c6',
                'x',
                'n',
                'v',
                'j1'
            ]
            var tmp = []
            var options = {
                host: 'download.finance.yahoo.com',
                port: 80,
                path: '/d/quotes.csv?f=' + params.join('') + '&s=' + encodeURIComponent(args),
                method: 'GET',
                headers: {
                    'user-agent': 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
                }
            };

            var req = http.request(options,
                function(res) {
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        tmp.push(chunk);
                    });

                    res.on('end', function (e) {
                        var body = tmp.join('');
                        var raw_list = body.trim().replace(/"/g, '').split(',');
                        var price = raw_list[1];
                        price = price.replace(/N\/A - /, '');
                        price = price.replace(/<b>/, '');
                        price = price.replace(/<\/b>/, '');
                        var perc = raw_list[2].replace(/N\/A - /, '');
                        var message = raw_list[5] + " (" + raw_list[0] + ") " + price + " " + raw_list[3] + " (" + perc + ") http://finance.yahoo.com/q?s=" + raw_list[0];
                        finishCall(message);
                    });
                }
            ).on("error", function (e) {
                finishCall("Got error: " + e.message);
            });
            req.end();
            break;
        case 'learn':
            var arg_parts = args.split(" "),
                command = arg_parts[0],
                response = arg_parts.slice(1).join(" ");
            learn(nick, command, response);
            break;
        default:
            respond(nick, command);
            break;
    }
});

module.exports = router;
<commit_msg>Error handling<commit_after>var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('pluses.db');
var express = require('express');
var router = express.Router();
var request = require('request');
var http = require('http');
var querystring = require('querystring');
var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
var image_index = 0;
var rando = false;

router.post('/', function(req, res) {
	// Replace spaces in request
	var term = req.body.text.replace(/^\./g, ''),
        parts = term.split(" "),
        command = parts[0],
        args = parts.slice(1).join(" "),
		finishCall = function(item) {
			res.end(JSON.stringify({text: item}));
		};
    if (parts[1]) {
        var nick = parts[1],
            nick = nick.replace(/[^a-zA-z0-9_ \.-]/g, '');
    }
    var leaderboard = function (table) {
        db.all("SELECT nick, pluses FROM " + table + " ORDER BY pluses DESC LIMIT 10", function (err, rows) {
            var leaders = table.charAt(0).toUpperCase() + table.slice(1) + " Leaderboard:\n";
            var i = 0;
            rows.forEach(function (row) {
                i++;
                leaders += i + ". " + row.pluses + " " + row.nick + "\n";
            });
            finishCall(leaders);
        });
    }

    var add_one = function(table, nick, req) {
        if (nick != req.body.user_name) {
            console.log("|" + nick + "| incremented " + table);
            db.run("INSERT OR IGNORE INTO " + table + " VALUES (?, 0)", nick);
            db.run("UPDATE " + table + " SET pluses = pluses + 1 WHERE nick = ?", nick);

            db.get("SELECT pluses FROM " + table + " WHERE nick = ?", nick, function (err, row) {
                finishCall(nick + " now has " + row.pluses + " " + table);
            });
        } else {
            finishCall("nice try");
        }
    }

    var sub_one = function(table, nick, req) {
        console.log("|" + req.body.user_name + "| tried to decrement" + table);
        db.run("INSERT OR IGNORE INTO " + table + " VALUES (?, 0)", req.body.user_name);
        db.run("UPDATE " + table + " SET pluses = pluses - 1 WHERE nick = ?", req.body.user_name);

        db.get("SELECT pluses FROM " + table + " WHERE nick = ?", req.body.user_name, function (err, row) {
            finishCall("Don't be a meanie! " + req.body.user_name + " now has " + row.pluses + " " + table);
        });
    }

    var learn = function(nick, command, response) {
        db.run("INSERT OR IGNORE INTO commands VALUES (?, ?, ?)", nick, command, response);
        finishCall("Learned command: " + command);
    }

    var respond = function(nick, command) {
        db.get("SELECT response FROM commands WHERE command = ? ORDER BY RANDOM() LIMIT 1", command, function (err, row) {
            if (row) {
                finishCall(row.response);
            } else {
                finishCall("I don't know how to " + command);
            }
        });
    }

    switch (command) {
        case "increment":
        case "pluses":
        case "plus":
            if (!nick) {
                leaderboard("pluses");
            } else {
                add_one("pluses", nick, req);
            }
            break;
        case "decrement":
            sub_one("pluses", nick, req);
            break;
        case "troll":
        case "trolls":
            if (!nick) {
                leaderboard("trolls");
            } else {
                add_one("trolls", nick);
            }
            break;
        case "resummon":
            rando = true;
        case "summon":
        case "gif":
            if (0 && req.body.user_name == "travis") {
                finishCall("http://4.bp.blogspot.com/_Nu9qz3BZvZU/S427XIB031I/AAAAAAAAAPg/38S5euCch7k/s400/justin_bieber_wallpaper_album_2009.jpg");
                break;
            }
            var options = {
                host: 'www.google.com',
                port: 80,
                path: "/search?safe=strict&tbm=isch&q=" + encodeURIComponent(args),
                method: 'GET',
                headers: {
                    'user-agent': 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
                }
            };
            var tmpist = [];
            var req = http.get(options,
                function(res) {
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        tmpist.push(chunk);
                    });

                    res.on('end', function (e) {
                        chunk = tmpist.join('');

                        var matches = chunk.match(/imgurl=(.*?)&/g);
                        if (matches) {
                            if (rando) {
                                image_index = Math.floor(Math.random() * matches.length);
                            }
                            var match = matches[image_index];
                            console.log(match);
                            rando = false;
                            finishCall(match.replace(/^imgurl=/, '').replace(/&$/, ''));
                        }
                    });
                }
            ).on("error", function (e) {
                finishCall("Got error: " + e.message);
            });

            break;
        case 'g':
        case 'google':
            var tmp = []
            var options = {
                host: 'ajax.googleapis.com',
                port: 80,
                path: '/ajax/services/search/web?v=1.0&rsz=large&start=0&q=' + encodeURIComponent(args),
                method: 'GET',
                headers: {
                    'user-agent': 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
                }
            };
            var req = http.request(options,
                function(res) {
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        tmp.push(chunk);
                    });

                    res.on('end', function (e) {
                        var body = tmp.join('');
                        var result = JSON.parse(body);
                        finishCall(
                            result.responseData.results[0].titleNoFormatting + " @ " +
                            result.responseData.results[0].unescapedUrl
                        );
                    });
                }
            ).on("error", function (e) {
                finishCall("Got error: " + e.message);
            });
            req.end();
            break;
        case 'source':
            finishCall('https://github.com/jayson/SlackCat');
            break;
        case 'gitup':
            exec("git pull", function (error, stdout, stderr) {
                finishCall(stdout + "\n" + stderr);
            });
            break;
        case 'youtube':
            exec("./youtube.py " + args, function (error, stdout, stderr) {
                finishCall(stdout + "\n" + stderr);
            });
            break;
        case 'q':
        case 'quote':
            var symbol = args.replace(/\./, '-');
            var params = [
                's',
                'k1',
                'k2',
                'c6',
                'x',
                'n',
                'v',
                'j1'
            ]
            var tmp = []
            var options = {
                host: 'download.finance.yahoo.com',
                port: 80,
                path: '/d/quotes.csv?f=' + params.join('') + '&s=' + encodeURIComponent(args),
                method: 'GET',
                headers: {
                    'user-agent': 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
                }
            };

            var req = http.request(options,
                function(res) {
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        tmp.push(chunk);
                    });

                    res.on('end', function (e) {
                        var body = tmp.join('');
                        var raw_list = body.trim().replace(/"/g, '').split(',');
                        var price = raw_list[1];
                        price = price.replace(/N\/A - /, '');
                        price = price.replace(/<b>/, '');
                        price = price.replace(/<\/b>/, '');
                        var perc = raw_list[2].replace(/N\/A - /, '');
                        var message = raw_list[5] + " (" + raw_list[0] + ") " + price + " " + raw_list[3] + " (" + perc + ") http://finance.yahoo.com/q?s=" + raw_list[0];
                        finishCall(message);
                    });
                }
            ).on("error", function (e) {
                finishCall("Got error: " + e.message);
            });
            req.end();
            break;
        case 'learn':
            var arg_parts = args.split(" "),
                command = arg_parts[0],
                response = arg_parts.slice(1).join(" ");
            learn(nick, command, response);
            break;
        default:
            respond(nick, command);
            break;
    }
});

module.exports = router;
<|endoftext|>


<commit_before>var debug 		= require('debug')('routers'),
	fs 			= require('fs'),
	util 		= require('util'),
	path 		= require('path'),
	multiparty 	= require('multiparty'),
	gm 			= require('gm'),
	imageMagick	= gm.subClass({ imageMagick : true}),
	mime		= require('mime'),
	Picture 	= require('../models/picture'),
	uploadDir	= './public/images/jumpingPics';

// Create an express router

var express 	= require('express'),
	router 		= express.Router();

// Log that router is starting

router.use(function(req,res,next){
	debug('Routing request.');
	next();
})

// Create s3 client

var	AWS			= require('aws-sdk'),
	s3 = new AWS.S3({
		accessKeyId: process.env.s3_access_key_ID,
		secretAccessKey: process.env.s3_secret_access_key
	}),
	s3_base_url = 'https://s3-us-west-1.amazonaws.com/' + process.env.s3_bucket + '/';

// Upload picture to AWS S3

router.post('/upload', function(req,res,next) {
	var form = new multiparty.Form({uploadDir:uploadDir});
	fs.mkdir(uploadDir, function(err){
		if(err) {
			if(err.code != 'EEXIST'){ next(err) }
		}
	})
	form.parse(req, function(err, fields, files){
		if(err){ next(err) }

		// Helper function for altering filename of picture

		function extendFilename(file, addition) {
			return file.replace(path.extname(file), addition + path.extname(file));
		}

		function getImageUrl(file, cb) {
			data = {
				Bucket : process.env.s3_bucket,
				Key : file
			};
			result = s3.getSignedUrl('getObject', data);
			cb(result);
		}

		// Get all form data
		var title 		= fields.title,
			description = fields.description,
			x			= fields.xData,
			y			= fields.yData,
			width		= fields.widthData,
			height		= fields.heightData,
			rotation	= fields.rotation;
		console.log(title + description + x + y + width + height + rotation);

		var picture = files.picture[0].path,
			fullSize = path.basename(picture),
			thumb = extendFilename(fullSize, '_thumb'),
			mimeType = mime.lookup(picture);

		// Resize and crop picture from crop and rotate data
		imageMagick(picture)
		.rotate('black', rotation)
		.crop(width, height, x, y)
		.stream(function(err, stdout, stderr) {
			if(err) next(err);

			var buf = new Buffer('');
			stdout.on('data', function(data){
				buf = Buffer.concat([buf, data]);
			});

			stdout.on('end', function(data){
				data = {
					Bucket : process.env.s3_bucket,
					Key : fullSize,
					Body : buf,
					ContentType : mimeType,
					ACL: 'public-read'
				};

				s3.putObject(data, function(err,res){
					if(err) next (err)
					console.log('file "' + fullSize +'" uploaded');
				});
			});
			// Resize picture for thumb
			imageMagick(stdout)
			.resize(500)
			.stream(function(err, stdout, stderr) {
				if(err) next(err);

				var buf = new Buffer('');
				stdout.on('data', function(data){
					buf = Buffer.concat([buf, data]);
				});
				stdout.on('end', function(data){
					data = {
						Bucket : process.env.s3_bucket,
						Key : thumb,
						Body : buf,
						ContentType : mimeType,
						ACL: 'public-read'
					};

					s3.putObject(data, function(err,res){
						if(err) next(err);
						console.log('file "' + thumb +'" uploaded');

						//Save picture to database
						var picture = new Picture({
							title: title,
							description: description,
							fullSize_url: s3_base_url + fullSize,
							thumb_url: s3_base_url + thumb
						});
						picture.save();
						console.log('Picture Saved');
					});
				});
			})
			res.redirect('..');
		});
	});
});

// Router for GET request of homepage

router.get('/', function(req,res,next){
	debug("GET '/'");
	Picture.find().sort('-dateAdded').exec(function(err, pictures){
		res.render('home', {title : 'Jumping is Fun!', pictures : pictures});	// Render homepage
	});
});

exports.router = router;<commit_msg>Changed tmp directory so heroku will work god damn it<commit_after>var debug 		= require('debug')('routers'),
	fs 			= require('fs'),
	util 		= require('util'),
	path 		= require('path'),
	multiparty 	= require('multiparty'),
	gm 			= require('gm'),
	imageMagick	= gm.subClass({ imageMagick : true}),
	mime		= require('mime'),
	Picture 	= require('../models/picture'),

// Create an express router

var express 	= require('express'),
	router 		= express.Router();

// Log that router is starting

router.use(function(req,res,next){
	debug('Routing request.');
	next();
})

// Create s3 client

var	AWS			= require('aws-sdk'),
	s3 = new AWS.S3({
		accessKeyId: process.env.s3_access_key_ID,
		secretAccessKey: process.env.s3_secret_access_key
	}),
	s3_base_url = 'https://s3-us-west-1.amazonaws.com/' + process.env.s3_bucket + '/';

// Upload picture to AWS S3

router.post('/upload', function(req,res,next) {
	var form = new multiparty.Form();
	fs.mkdir(uploadDir, function(err){
		if(err) {
			if(err.code != 'EEXIST'){ next(err) }
		}
	})
	form.parse(req, function(err, fields, files){
		if(err){ next(err) }

		// Helper function for altering filename of picture

		function extendFilename(file, addition) {
			return file.replace(path.extname(file), addition + path.extname(file));
		}

		function getImageUrl(file, cb) {
			data = {
				Bucket : process.env.s3_bucket,
				Key : file
			};
			result = s3.getSignedUrl('getObject', data);
			cb(result);
		}

		// Get all form data
		var title 		= fields.title,
			description = fields.description,
			x			= fields.xData,
			y			= fields.yData,
			width		= fields.widthData,
			height		= fields.heightData,
			rotation	= fields.rotation;
		console.log(title + description + x + y + width + height + rotation);

		var picture = files.picture[0].path,
			fullSize = path.basename(picture),
			thumb = extendFilename(fullSize, '_thumb'),
			mimeType = mime.lookup(picture);

		// Resize and crop picture from crop and rotate data
		imageMagick(picture)
		.rotate('black', rotation)
		.crop(width, height, x, y)
		.stream(function(err, stdout, stderr) {
			if(err) next(err);

			var buf = new Buffer('');
			stdout.on('data', function(data){
				buf = Buffer.concat([buf, data]);
			});

			stdout.on('end', function(data){
				data = {
					Bucket : process.env.s3_bucket,
					Key : fullSize,
					Body : buf,
					ContentType : mimeType,
					ACL: 'public-read'
				};

				s3.putObject(data, function(err,res){
					if(err) next (err)
					console.log('file "' + fullSize +'" uploaded');
				});
			});
			// Resize picture for thumb
			imageMagick(stdout)
			.resize(500)
			.stream(function(err, stdout, stderr) {
				if(err) next(err);

				var buf = new Buffer('');
				stdout.on('data', function(data){
					buf = Buffer.concat([buf, data]);
				});
				stdout.on('end', function(data){
					data = {
						Bucket : process.env.s3_bucket,
						Key : thumb,
						Body : buf,
						ContentType : mimeType,
						ACL: 'public-read'
					};

					s3.putObject(data, function(err,res){
						if(err) next(err);
						console.log('file "' + thumb +'" uploaded');

						//Save picture to database
						var picture = new Picture({
							title: title,
							description: description,
							fullSize_url: s3_base_url + fullSize,
							thumb_url: s3_base_url + thumb
						});
						picture.save();
						console.log('Picture Saved');
					});
				});
			})
			res.redirect('..');
		});
	});
});

// Router for GET request of homepage

router.get('/', function(req,res,next){
	debug("GET '/'");
	Picture.find().sort('-dateAdded').exec(function(err, pictures){
		res.render('home', {title : 'Jumping is Fun!', pictures : pictures});	// Render homepage
	});
});

exports.router = router;<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

var mongoose = require('mongoose');
var Food = mongoose.model('Food');
var Recipe = mongoose.model('Recipe');

// GET home page.
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Time Crunch' });
});

// Param function for selecting food objects
router.param('food', function(req, res, next, id) {
    var query = Food.findById(id);

    query.exec(function (err, food){
        if (err) { return next(err); }
        if (!food) { return next(new Error('can\'t find food')); }

        req.food = food
        return next();
    });
});

// GET all food
router.get('/food', function(req, res, next) {
    Food.find(function(err, food){
        if(err){
            return next(err);
        }
        res.json(food);
    });
});

// POST food
router.post('/food', function(req, res, next) {
    var food = new Food(req.body);

    food.save(function(err, food){
        if(err) {
            return next(err);
        }
        res.json(food);
    });
});

module.exports = router;
<commit_msg>Added DELETE food route<commit_after>var express = require('express');
var router = express.Router();

var mongoose = require('mongoose');
var Food = mongoose.model('Food');
var Recipe = mongoose.model('Recipe');

// GET home page.
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Time Crunch' });
});

// Param function for selecting food objects
router.param('food', function(req, res, next, id) {
    var query = Food.findById(id);

    query.exec(function (err, food){
        if (err) { return next(err); }
        if (!food) { return next(new Error('can\'t find food')); }

        req.food = food
        return next();
    });
});

// GET all food
router.get('/food', function(req, res, next) {
    Food.find(function(err, food){
        if(err){
            return next(err);
        }
        res.json(food);
    });
});

// POST food
router.post('/food', function(req, res, next) {
    var food = new Food(req.body);

    food.save(function(err, food){
        if(err) {
            return next(err);
        }
        res.json(food);
    });
});

// DELETE food
router.delete('/food/:food', function(req, res, next) {
    Food.remove({_id: req.food}, function(err) {
        if(err) {
            res.send(err);
        }
        res.sendStatus(204);
    });
});

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'new easysublease.org listing page demo',
    online_sample:"55910d94008d84ed2912e1ae",
    local_sample:"5593aa9e48f2890a9a0f2929"
   });
});

module.exports = router;
<commit_msg>listing.easysublease.com registered<commit_after>var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'new easysublease.org listing page demo',
    online_sample:"559418e1731b61add4b8d532",
    local_sample:"5593aa9e48f2890a9a0f2929"
   });
});

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var request = require('request');
var Step = require('step');

var OUR_GROUP_URL_NAME = 'Fayetteville-Startup-Video-Game-Company-Meetup';

// converts military time to standard time
// accepts a string in these formats:
//   HH:mm:ss
//   HH:mm
// returns an object in this format:
//   hour: HH
//   min:  mm
//   period: am | pm
function convertMilitaryTime(time) {

    // splits the time into an array using the colon as separator
    var splitTime = time.split(':');

    // converts the strings to integers
    var hour = parseInt(splitTime[0]);
    var min = splitTime[1];
    var period = '';

    // converts the hour from military time to standard time
    if (hour === 0) {
        hour = 12;
        period = 'am';
    } else if (hour <= 11) {
        period = 'am';
    } else if (hour === 12) {
        period = 'pm';
    } else if (hour > 12) {
        hour = hour - 12;
        period = 'pm';
    }

    // creates the converted time object and returns it
    var convertedTime = {
        hour: hour.toString(),
        min: min,
        period: period
    };

    return convertedTime;
}

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index');
});

// /* GET meetup page */
 router.get('/meetup', function(req, res) {

    // use Step to synchronize the API call
    // so we don't try to process data until
    // we've received it
    Step(
        function getMeetupData() {

            var self = this;

            var meetupApiUrl = 'https://api.meetup.com/2/events?group_urlname='
            + OUR_GROUP_URL_NAME
            + '&status=upcoming&page=1';

            // uses the request Node library to send the get request
            request.get(meetupApiUrl, function(error, response, jsonData) {

                // if successful, pass along the jsonData
                // else, pass along an error
                if (!error && response.statusCode == 200) {
                    self(null, jsonData);
                    console.log(jsonData);
                } else {
                    self(error, jsonData);
                }
            });
        },
        function processMeetupData(err, meetupDataJSON) {

            // Uh oh, there's an error.
            // Render the error template.
            if (err !== null) {

                res.render('error', {
                    message: 'Error getting data from Meetup.',
                    error: err
                });
            // No error.
            // Render the meetup template.
            } else {

                // need to parse the JSON to de-serialize it
                // from a string to an object we can work with
                // Thank you, Blake. -- Roy :-)
                dataJSON = JSON.parse(meetupDataJSON);
console.log(dataJSON);
                // meetup time is in format of milliseconds since epoch
                // convert to local date time
                // var msUTC = dataJSON.results[0].time;
                // // create a new date time object and set it to the epoch
                // var localDateTime = new Date(0);
                // // add the number of milliseconds to it to get the local date time
                // localDateTime.setMilliseconds(msUTC);
                //
                // // break the localDateTime down into separate variables
                // localDateTime = localDateTime.toString();
                // var splitDateTime = localDateTime.split(' ');
                // var eventWeekDay = splitDateTime[0];
                // var eventMonth = splitDateTime[1];
                // var eventDay = splitDateTime[2];
                // var eventYear = splitDateTime[3];
                //
                // // time is in military time
                // // break the event time down into hours, minutes, and period
                // var eventTime = convertMilitaryTime(splitDateTime[4]);
                //
                // // meetup event duration is in the format of milliseconds
                // // convert to hours
                // var duration = ((dataJSON.results[0].duration / 1000) / 60) / 60;

                // send the raw JSON data to the browser
                // res.status(200);
                // res.type('json');
                // res.send(meetupDataJSON);
                // res.end();
                  if(dataJSON.results.length  ===0) {
                    res.send('We will change this to render the jade page... The time creation above is having an issue');
                  } else {

                // send the data to the view with variables
                res.render('meetup', {name: dataJSON.results[0].name,
                                      description: dataJSON.results[0].description,
                                      eventURL: dataJSON.results[0].event_url,
                                      venueName: dataJSON.results[0].venue.name,
                                      venueAddress: dataJSON.results[0].venue.address_1,
                                      venueCity: dataJSON.results[0].venue.city,
                                      venueState: dataJSON.results[0].venue.state.toUpperCase(),
                                      venueZip: dataJSON.results[0].venue.zip,
                                      venueLatitude: dataJSON.results[0].venue.lat,
                                      venueLongitude: dataJSON.results[0].venue.lon,
                                      groupName: dataJSON.results[0].group.name,
                                      groupUrlName: dataJSON.results[0].group.urlname,
                                      eventDuration: duration,
                                      eventWeekDay: eventWeekDay,
                                      eventMonth: eventMonth,
                                      eventDay: eventDay,
                                      eventYear: eventYear,
                                      eventStartHour: eventTime.hour,
                                      eventStartMin: eventTime.min,
                                      eventStartPeriod: eventTime.period
                                     });
                                   }
            }
        }
    );

 });

module.exports = router;
<commit_msg>Fixed my no event mistake. Moved the checker above the time portion.<commit_after>var express = require('express');
var router = express.Router();
var request = require('request');
var Step = require('step');

var OUR_GROUP_URL_NAME = 'Free-Code-Camp-NWA';

// converts military time to standard time
// accepts a string in these formats:
//   HH:mm:ss
//   HH:mm
// returns an object in this format:
//   hour: HH
//   min:  mm
//   period: am | pm
function convertMilitaryTime(time) {

    // splits the time into an array using the colon as separator
    var splitTime = time.split(':');

    // converts the strings to integers
    var hour = parseInt(splitTime[0]);
    var min = splitTime[1];
    var period = '';

    // converts the hour from military time to standard time
    if (hour === 0) {
        hour = 12;
        period = 'am';
    } else if (hour <= 11) {
        period = 'am';
    } else if (hour === 12) {
        period = 'pm';
    } else if (hour > 12) {
        hour = hour - 12;
        period = 'pm';
    }

    // creates the converted time object and returns it
    var convertedTime = {
        hour: hour.toString(),
        min: min,
        period: period
    };

    return convertedTime;
}

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index');
});

// /* GET meetup page */
 router.get('/meetup', function(req, res) {

    // use Step to synchronize the API call
    // so we don't try to process data until
    // we've received it
    Step(
        function getMeetupData() {

            var self = this;

            var meetupApiUrl = 'https://api.meetup.com/2/events?group_urlname='
            + OUR_GROUP_URL_NAME
            + '&status=upcoming&page=1';

            // uses the request Node library to send the get request
            request.get(meetupApiUrl, function(error, response, jsonData) {

                // if successful, pass along the jsonData
                // else, pass along an error
                if (!error && response.statusCode == 200) {
                    self(null, jsonData);
                    console.log(jsonData);
                } else {
                    self(error, jsonData);
                }
            });
        },
        function processMeetupData(err, meetupDataJSON) {

            // Uh oh, there's an error.
            // Render the error template.
            if (err !== null) {

                res.render('error', {
                    message: 'Error getting data from Meetup.',
                    error: err
                });
            // No error.
            // Render the meetup template.
            } else {

                // need to parse the JSON to de-serialize it
                // from a string to an object we can work with
                // Thank you, Blake. -- Roy :-)
                dataJSON = JSON.parse(meetupDataJSON);
console.log(dataJSON);

if(dataJSON.results.length  ===0) {
  res.send('We will change this to render the jade page...');
} else {
                // meetup time is in format of milliseconds since epoch
                // convert to local date time
                var msUTC = dataJSON.results[0].time;
                // create a new date time object and set it to the epoch
                var localDateTime = new Date(0);
                // add the number of milliseconds to it to get the local date time
                localDateTime.setMilliseconds(msUTC);

                // break the localDateTime down into separate variables
                localDateTime = localDateTime.toString();
                var splitDateTime = localDateTime.split(' ');
                var eventWeekDay = splitDateTime[0];
                var eventMonth = splitDateTime[1];
                var eventDay = splitDateTime[2];
                var eventYear = splitDateTime[3];

                // time is in military time
                // break the event time down into hours, minutes, and period
                var eventTime = convertMilitaryTime(splitDateTime[4]);

                // meetup event duration is in the format of milliseconds
                // convert to hours
                var duration = ((dataJSON.results[0].duration / 1000) / 60) / 60;

                // send the raw JSON data to the browser
                // res.status(200);
                // res.type('json');
                // res.send(meetupDataJSON);
                // res.end();

                // send the data to the view with variables
                res.render('meetup', {name: dataJSON.results[0].name,
                                      description: dataJSON.results[0].description,
                                      eventURL: dataJSON.results[0].event_url,
                                      venueName: dataJSON.results[0].venue.name,
                                      venueAddress: dataJSON.results[0].venue.address_1,
                                      venueCity: dataJSON.results[0].venue.city,
                                      venueState: dataJSON.results[0].venue.state.toUpperCase(),
                                      venueZip: dataJSON.results[0].venue.zip,
                                      venueLatitude: dataJSON.results[0].venue.lat,
                                      venueLongitude: dataJSON.results[0].venue.lon,
                                      groupName: dataJSON.results[0].group.name,
                                      groupUrlName: dataJSON.results[0].group.urlname,
                                      eventDuration: duration,
                                      eventWeekDay: eventWeekDay,
                                      eventMonth: eventMonth,
                                      eventDay: eventDay,
                                      eventYear: eventYear,
                                      eventStartHour: eventTime.hour,
                                      eventStartMin: eventTime.min,
                                      eventStartPeriod: eventTime.period
                                     });
                                   }
            }
        }
    );

 });

module.exports = router;
<|endoftext|>


<commit_before>'use strict'

const { Router } = require('express')
const router = Router()

router.use(require('./auth-route'))
router.use(require('./games-route'))
router.use(require('./words-route'))
// router.use(require('./friends-route'))

router.get('/', (req,res) => {
  res.json ({
    "login": "/api/v1/auth/login",
    "register": "/api/v1/auth/register",
    "getLoggedInUser": "/api/v1/auth/user",
    "getGamesForLoggedInUser": "/api/v1/user/games",
    "getFriendsForLoggedInUser": "/api/v1/user/friends",
    "getAllgames": "/api/v1/games",
    "getWord" : "/api/v1/word/:<correct_word>",
    "addWord": "/api/v1/words/new",
    "addGame": "/api/v1/games/new",
    "updateGame": "/api/v1/games/:<gameId>",
    "getWordsForSpecifiedGame": "/api/v1/games/words?gameId=<gameId>"
  })
})

module.exports = router;
<commit_msg>changed urls for release<commit_after>'use strict'

const { Router } = require('express')
const router = Router()

router.use(require('./auth-route'))
router.use(require('./games-route'))
router.use(require('./words-route'))
// router.use(require('./friends-route'))

router.get('/', (req,res) => {
  res.json ({
    "login": "https://warm-harbor-25906.herokuapp.com/api/v1/auth/login",
    "register": "https://warm-harbor-25906.herokuapp.com/api/v1/auth/register",
    "getLoggedInUser": "https://warm-harbor-25906.herokuapp.com/api/v1/auth/user",
    "getGamesForLoggedInUser": "https://warm-harbor-25906.herokuapp.com/api/v1/user/games",
    "getFriendsForLoggedInUser": "https://warm-harbor-25906.herokuapp.com/api/v1/user/friends",
    "getAllgames": "https://warm-harbor-25906.herokuapp.com/api/v1/games",
    "getWord" : "https://warm-harbor-25906.herokuapp.com/api/v1/word/:<correct_word>",
    "addWord": "https://warm-harbor-25906.herokuapp.com/api/v1/words/new",
    "addGame": "https://warm-harbor-25906.herokuapp.com/api/v1/games/new",
    "updateGame": "https://warm-harbor-25906.herokuapp.com/api/v1/games/:<gameId>",
    "getWordsForSpecifiedGame": "https://warm-harbor-25906.herokuapp.com/api/v1/games/words?gameId=<gameId>"
  })
})

module.exports = router;
<|endoftext|>


<commit_before>//= require polyline

var directionsService = new google.maps.DirectionsService();

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();

  var mapOptions = {
    zoom: 4,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
  directionsDisplay.setMap(map);
  route = new Route();
  route.calculateRoute();

}

//-------Route----------

var Route = function(){
  this.start = new google.maps.LatLng(41.953819, -87.654750), // Chicago for now
  this.end = new google.maps.LatLng(38.637548, -90.205010), // St. Louis for now
  this.waypts = this.getWaypoints();
};

Route.prototype.getWaypoints = function(){
  var waypts = [];
  var checkboxArray = document.getElementById('waypoints');

  for (var i = 0; i < checkboxArray.length; i++) {
    if (checkboxArray.options[i].selected == true) {
      waypts.push({
        location: checkboxArray[i].value,
        stopover: true});
    }
  }

  return waypts;
};

Route.prototype.calculateRoute = function(){
  var request = {
    origin: this.start,
    destination: this.end,
    waypoints: this.waypts,
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.DRIVING
  };

  directionsService.route(request, function(response, status){
    if (status == google.maps.DirectionsStatus.OK) {

      decoder = new PolylineDecoder()
      route.polyline = decoder.decodePolyline(response);
      polygon = new Polygon(route.polyline)
      route.displayRoute(response, true)
    }
  });
};

Route.prototype.displayRoute = function(response, drawMe){
  drawMe = typeof drawMe !== 'undefined' ? drawMe : true;

  directionsDisplay.setDirections(response);

  if (drawMe) {
    drawer = new Drawer();
    drawer.draw(polygon.geoJson);
  };
}

//----polyline decoder-----

var PolylineDecoder = function(response){}

PolylineDecoder.prototype.decodePolyline = function(response){
  var coord_array = polyline.decode(response.routes[0].overview_polyline);
  return coord_array.map(function(coordinate) {
    return [coordinate[1], coordinate[0]];
  })
}

//-------Polygon!------------

var Polygon = function(polyline){
  this.geoJson = this.createGeoJsonFromPolyline(polyline)
  this.searchWithin(this.geoJson)
}

Polygon.prototype.createGeoJsonFromPolyline = function(polyline) {
  var line = {
    type:"Feature",
    geometry:{
      type:"LineString",
      coordinates: polyline
     }
   }

  var polygon = turf.buffer(line, 25, 'miles')
  return polygon
}

Polygon.prototype.searchWithin = function(polygon){
  $.ajax({
  url: '/maps/search',
  type: 'post',
  beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content'))},
  contentType: "application/json",
  dataType: "json",
  data: JSON.stringify(polygon),
})
  .success(function(response){
    loadMarkers(response.attractions)
  })
}

//---------Draw-er---------------------
var Drawer = function(){}

Drawer.prototype.createLatLongObjects = function(geoJsonObject){
  var latLongArray = []
  var coordArray = geoJsonObject.features[0].geometry.coordinates[0]

  coordArray.forEach(function(coord){
    latLongArray.push(new google.maps.LatLng(coord[1], coord[0]))
    return latLongArray
  })
  return latLongArray
}

Drawer.prototype.draw = function(geoJsonObject){
  var coordsToDraw = this.createLatLongObjects(geoJsonObject)

    bufferedPolygon = new google.maps.Polygon({
    paths: coordsToDraw,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  bufferedPolygon.setMap(map);

}

//------------Markers----------------

function loadMarkers(attractions){

    $.each(attractions, function(i,item){
      loadMarker(item);
    });
  }

function loadMarker(attraction){

  var latitude = attraction.longlat.coordinates[1];
  var longitude = attraction.longlat.coordinates[0];
  var coords = new google.maps.LatLng(latitude, longitude);

  var marker = new google.maps.Marker({
    position: coords,
    map: map
  });

  new InfoBox(attraction, marker)
}

//-----------InfoBox----------------
var InfoBox = function(attraction, marker){
  this.contentString ='
' +
                      '
' +
                      attraction.name +
                      '
' +
                      '
',
  this.popup = new google.maps.InfoWindow({content: this.contentString});
  this.addClickListener(marker)
}

InfoBox.prototype.addClickListener = function(marker){
  var myThis = this
  google.maps.event.addDomListener(marker, 'click', function(){
    myThis.popup.open(map, marker);
  });
}

//------------misc DOM operations-------------------

google.maps.event.addDomListener(window, 'load', initialize);

google.maps.event.addDomListener(window, "resize", function() {
    var center = map.getCenter();
    google.maps.event.trigger(map, "resize");
    map.setCenter(center);
  });<commit_msg>added ratings and reviews to infowindows for attractions<commit_after>//= require polyline

var directionsService = new google.maps.DirectionsService();

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();

  var mapOptions = {
    zoom: 4,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
  directionsDisplay.setMap(map);
  route = new Route();
  route.calculateRoute();

}

//-------Route----------

var Route = function(){
  this.start = new google.maps.LatLng(41.953819, -87.654750), // Chicago for now
  this.end = new google.maps.LatLng(38.637548, -90.205010), // St. Louis for now
  this.waypts = this.getWaypoints();
};

Route.prototype.getWaypoints = function(){
  var waypts = [];
  var checkboxArray = document.getElementById('waypoints');

  for (var i = 0; i < checkboxArray.length; i++) {
    if (checkboxArray.options[i].selected == true) {
      waypts.push({
        location: checkboxArray[i].value,
        stopover: true});
    }
  }

  return waypts;
};

Route.prototype.calculateRoute = function(){
  var request = {
    origin: this.start,
    destination: this.end,
    waypoints: this.waypts,
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.DRIVING
  };

  directionsService.route(request, function(response, status){
    if (status == google.maps.DirectionsStatus.OK) {

      decoder = new PolylineDecoder()
      route.polyline = decoder.decodePolyline(response);
      polygon = new Polygon(route.polyline)
      route.displayRoute(response, true)
    }
  });
};

Route.prototype.displayRoute = function(response, drawMe){
  drawMe = typeof drawMe !== 'undefined' ? drawMe : true;

  directionsDisplay.setDirections(response);

  if (drawMe) {
    drawer = new Drawer();
    drawer.draw(polygon.geoJson);
  };
}

//----polyline decoder-----

var PolylineDecoder = function(response){}

PolylineDecoder.prototype.decodePolyline = function(response){
  var coord_array = polyline.decode(response.routes[0].overview_polyline);
  return coord_array.map(function(coordinate) {
    return [coordinate[1], coordinate[0]];
  })
}

//-------Polygon!------------

var Polygon = function(polyline){
  this.geoJson = this.createGeoJsonFromPolyline(polyline)
  this.searchWithin(this.geoJson)
}

Polygon.prototype.createGeoJsonFromPolyline = function(polyline) {
  var line = {
    type:"Feature",
    geometry:{
      type:"LineString",
      coordinates: polyline
     }
   }

  var polygon = turf.buffer(line, 25, 'miles')
  return polygon
}

Polygon.prototype.searchWithin = function(polygon){
  $.ajax({
  url: '/maps/search',
  type: 'post',
  beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content'))},
  contentType: "application/json",
  dataType: "json",
  data: JSON.stringify(polygon),
})
  .success(function(response){
    loadMarkers(response.attractions)
  })
}

//---------Draw-er---------------------
var Drawer = function(){}

Drawer.prototype.createLatLongObjects = function(geoJsonObject){
  var latLongArray = []
  var coordArray = geoJsonObject.features[0].geometry.coordinates[0]

  coordArray.forEach(function(coord){
    latLongArray.push(new google.maps.LatLng(coord[1], coord[0]))
    return latLongArray
  })
  return latLongArray
}

Drawer.prototype.draw = function(geoJsonObject){
  var coordsToDraw = this.createLatLongObjects(geoJsonObject)

    bufferedPolygon = new google.maps.Polygon({
    paths: coordsToDraw,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  bufferedPolygon.setMap(map);

}

//------------Markers----------------

function loadMarkers(attractions){

    $.each(attractions, function(i,item){
      loadMarker(item);
    });
  }

function loadMarker(attraction){

  var latitude = attraction.longlat.coordinates[1];
  var longitude = attraction.longlat.coordinates[0];
  var coords = new google.maps.LatLng(latitude, longitude);

  var marker = new google.maps.Marker({
    position: coords,
    map: map
  });

  new InfoBox(attraction, marker)
}

//-----------InfoBox----------------
var InfoBox = function(attraction, marker){
  this.contentString ='
' +
                      '
' +
                      attraction.name +
                      '
' +
                      '
 Rating: ' +
                      attraction.rating +
                      '
' +
                      '
 Number of Reviews: ' +
                      attraction.review_count +
                      '
' +
                      '
',
  this.popup = new google.maps.InfoWindow({content: this.contentString});
  this.addClickListener(marker)
}

InfoBox.prototype.addClickListener = function(marker){
  var myThis = this
  google.maps.event.addDomListener(marker, 'click', function(){
    myThis.popup.open(map, marker);
  });
}

//------------misc DOM operations-------------------

google.maps.event.addDomListener(window, 'load', initialize);

google.maps.event.addDomListener(window, "resize", function() {
    var center = map.getCenter();
    google.maps.event.trigger(map, "resize");
    map.setCenter(center);
  });
<|endoftext|>


<commit_before>var express = require('express');
//var path = require('path');
var router = express.Router();
var connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/textlr';

/* GET home page. */
router.get('/', function(req, res, next) {
	res.render('index', {title: "Textlr"});
});

router.post('/', function(req, res, next) {
	// Thanks http://mherman.org/blog/2015/02/12/postgresql-and-nodejs/
	var pg = require('pg');
	var secrets = require('./secrets.js');
	var crypto = require('crypto');
	var marked = require('marked');
	marked.setOptions({
	  renderer: new marked.Renderer(),
	  gfm: true,
	  tables: true,
	  breaks: false,
	  pedantic: false,
	  sanitize: true,
	  smartLists: true,
	  smartypants: true
	});

	var nakedtext = req.body.text;
	var text = nakedtext;
	var title = '';

	if(nakedtext.charAt(0) == '#' && nakedtext.charAt(1) != '#') {
		var slashn = text.indexOf('\n');
		var slashr = text.indexOf('\r');

		if(slashn > slashr) {
			var a  = slashn;
			slashn = slashr;
			slashr = a;
		}
		var start = (nakedtext.charAt(1) == ' ' ? 2 : 1)

		title = text.slice(start,slashn);

		if(slashr - slashn == 1) {
			text = text.slice(slashr+1)
		} else {
			text = text.slice(slashn+1)
		}
	}

	var markedtext = marked(text);

    var hash = crypto.createHmac('sha512', secrets.secret);
	var when = (new Date).getTime() - secrets.textlrEpoch;
    hash.update(when.toString());
    var id = hash.digest('base64').substring(0,10).replace(/\//g, "=");

	pg.connect(connectionString, function(err, client, done) {
        if(err) {
          done();
          console.log(err);
          return res.status(500).json({ success: false, data: err});
        }

		if(title != '') {
			client.query({
				text:   "INSERT INTO texts(id,title,markedtext,nakedtext) VALUES ($1, $2, $3, $4)",
				name:   "add-text-with-title",
				values: [id, title, markedtext, nakedtext]
			});
		} else {
			client.query({
				text:   "INSERT INTO texts(id,markedtext,nakedtext) VALUES ($1, $2, $3)",
				name:   "add-text-without-title",
				values: [id, markedtext, nakedtext]
			});
		}

    });

	res.writeHead(302, {
		'Location': '/'+(title != '' ? encodeURIComponent(title).replace('%20','+').substring(0,35) + '/' : '')+id
	});
	res.end();
});

router.get(/^.*(.{10}$)/i, function(req, res, next) {
	var pg = require('pg');

	var id = req.params[0];

	pg.connect(connectionString, function(err, client, done) {
        if(err) {
          done();
          console.log(err);
          return res.status(500).json({ success: false, data: err});
        }

		var query = client.query({
			text:   "SELECT title,markedtext FROM texts WHERE id = $1",
			name:   "select-text",
			values: [id]
		});

		var found = 0;
		query.on('row', function(row) {
			if (found == 0) {
				var title = (row.title != null ? row.title : "Textlr");
				var text  = row.markedtext;

				res.render('text', {text: text, title: title});
			}
			found++;
		});

		query.on('end', function(result) {
			rowCount = result.rowCount;
			if(rowCount != 1) {
				return res.status(404).send("Not Found");
			}
		});
	});

});

module.exports = router;
<commit_msg>Deleted some unnecessary whitespace<commit_after>var express = require('express');
//var path = require('path');
var router = express.Router();
var connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/textlr';

/* GET home page. */
router.get('/', function(req, res, next) {
	res.render('index', {title: "Textlr"});
});

router.post('/', function(req, res, next) {
	// Thanks http://mherman.org/blog/2015/02/12/postgresql-and-nodejs/
	var pg = require('pg');
	var secrets = require('./secrets.js');
	var crypto = require('crypto');
	var marked = require('marked');
	marked.setOptions({
	  renderer: new marked.Renderer(),
	  gfm: true,
	  tables: true,
	  breaks: false,
	  pedantic: false,
	  sanitize: true,
	  smartLists: true,
	  smartypants: true
	});

	var nakedtext = req.body.text;
	var text = nakedtext;
	var title = '';

	if(nakedtext.charAt(0) == '#' && nakedtext.charAt(1) != '#') {
		var slashn = text.indexOf('\n');
		var slashr = text.indexOf('\r');

		if(slashn > slashr) {
			var a  = slashn;
			slashn = slashr;
			slashr = a;
		}
		var start = (nakedtext.charAt(1) == ' ' ? 2 : 1)

		title = text.slice(start,slashn);

		if(slashr - slashn == 1) {
			text = text.slice(slashr+1)
		} else {
			text = text.slice(slashn+1)
		}
	}

	var markedtext = marked(text);

    var hash = crypto.createHmac('sha512', secrets.secret);
	var when = (new Date).getTime() - secrets.textlrEpoch;
    hash.update(when.toString());
    var id = hash.digest('base64').substring(0,10).replace(/\//g, "=");

	pg.connect(connectionString, function(err, client, done) {
        if(err) {
          done();
          console.log(err);
          return res.status(500).json({ success: false, data: err});
        }

		if(title != '') {
			client.query({
				text:   "INSERT INTO texts(id,title,markedtext,nakedtext) VALUES ($1, $2, $3, $4)",
				name:   "add-text-with-title",
				values: [id, title, markedtext, nakedtext]
			});
		} else {
			client.query({
				text:   "INSERT INTO texts(id,markedtext,nakedtext) VALUES ($1, $2, $3)",
				name:   "add-text-without-title",
				values: [id, markedtext, nakedtext]
			});
		}

    });

	res.writeHead(302, {
		'Location': '/'+(title != '' ? encodeURIComponent(title).replace('%20','+').substring(0,35) + '/' : '')+id
	});
	res.end();
});

router.get(/^.*(.{10}$)/i, function(req, res, next) {
	var pg = require('pg');

	var id = req.params[0];

	pg.connect(connectionString, function(err, client, done) {
        if(err) {
          done();
          console.log(err);
          return res.status(500).json({ success: false, data: err});
        }

		var query = client.query({
			text:   "SELECT title,markedtext FROM texts WHERE id = $1",
			name:   "select-text",
			values: [id]
		});

		var found = 0;
		query.on('row', function(row) {
			if (found == 0) {
				var title = (row.title != null ? row.title : "Textlr");
				var text  = row.markedtext;

				res.render('text', {text: text, title: title});
			}
			found++;
		});

		query.on('end', function(result) {
			rowCount = result.rowCount;
			if(rowCount != 1) {
				return res.status(404).send("Not Found");
			}
		});
	});
});

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var config = (process.env.HEROKU) ? {dbkey : process.env.DBKEY} : require('./config.js');
var db = require('orchestrate')(config.dbkey);
var passport = require('passport');
var util = require('util');
var session = require('express-session');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var GitHubStrategy = require('passport-github2').Strategy;
var partials = require('express-partials');
var logger = require('morgan');
var cookieParser = require('cookie-parser');

//----------Github passport things----------------
var GITHUB_CLIENT_ID = config.github_client_id;
var GITHUB_CLIENT_SECRET = config.github_client_secret;

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

passport.use('github', new GitHubStrategy({
    clientID: GITHUB_CLIENT_ID,
    clientSecret: GITHUB_CLIENT_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/github/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    process.nextTick(function () {
      return done(null, profile);
    });
  }
));

router.use(passport.initialize());
router.use(passport.session());
router.use(logger('dev'));
router.use(cookieParser());

//----------------------------------------------

router.get('/', function(req, res, next) {
  if(req.user){
    console.log("cookie", req.cookies.user);
    res.render('user_session', { title: "Hello, " + req.user.displayName ,layout: 'layout', logged_user:req.cookies.url , banana:'yellow' , client_user_session: true});
  }
  else{
    console.log("!req.user");
    res.render('index', { title: 'OPP' , layout: 'layout' , banana:'red' , client_user_session: false });
  }
});

router.get('/test', function(req, res, next) {
  res.render('index', { title: 'OPP' , layout: 'tests_layout'});
});

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    // console.log("req.path: ", req.path);
    req.session.returnTo = req.path;
    return next();
  }
  else {
    console.log("ensure authentication failed");
  }
}

router.put("/profiles/:id", ensureAuthenticated, function(req, res, next){
    var id = req.params.id;

    console.log("profile updated(not really)");
    // console.log("request body", req.body);
    console.log("title:", req.body.title);
    console.log("twitter:", req.body.twitter_url);
    console.log("linkedin_url:", req.body.linkedin_url);
    console.log("personal_site_url:", req.body.personal_site_url);
    console.log("top_skills:", req.body.top_skills);
    console.log("top_tools:", req.body.top_tools);

    db.newPatchBuilder("OPP_users", id)
      .replace("profile_content.social_urls.twitter", req.body.twitter_url)
      .replace("profile_content.social_urls.linkedin", req.body.linkedin_url)
      .replace("profile_content.editable_text.title", req.body.title)
      .replace("profile_content.social_urls.personal", req.body.personal_site_url)
      .replace("profile_content.editable_text.skills", req.body.top_skills)
      .replace("profile_content.editable_text.tools", req.body.top_tools)
      .apply()
      .fail(function(err){
        console.log("profiles update failed");
        send(err);
      });
});

router.get('/profiles', function(req, res, next) {
  db.list('OPP_users')
      .then(function (result) {
        var data = result.body.results;
        var mapped = data.map(function (element, index) {
          // if(element.value.active === true){
          return {
            id: element.path.key,
            name: element.value.profile_content.editable_text.name ,
            title: element.value.profile_content.editable_text.title ,
            github_url: element.value.github_api_data.github_url ,
            profile_img_url: element.value.profile_content.img_urls.profile_img ,
            personal_site_url: element.value.profile_content.social_urls.personal ,
            linkedin_url: element.value.profile_content.social_urls.linkedin ,
            twitter_url: element.value.profile_content.social_urls.twitter ,
            url_id: element.value.profile_content.editable_text.url_id ,
            top_skills: element.value.profile_content.editable_text.skills ,
            top_tools: element.value.profile_content.editable_text.tools ,
            js_tidbit: element.value.profile_content.editable_text.q_and_a.js_tidbit ,
            work_status: element.value.profile_content.checkbox_content.work_status ,
            dream_job: element.value.profile_content.editable_text.q_and_a.job_hope
          };
        // }
      });
        // console.log("mapped: ", mapped);
        res.send(mapped);
      })
      .fail(function(err){
        console.log("profiles get failed:", err);
        send(err);
      });
});

router.put("/projects/:id", ensureAuthenticated, function(req, res, next){
    var id = req.params.id;

    console.log("project updated(not really)");
    console.log("title:", req.body.title);
    console.log("project_url_id:", req.body.project_url_id);
    console.log("mvp:", req.body.mvp);
    console.log("tech_used:", req.body.tech_used);

    // db.newPatchBuilder("OPP_projects", id)
    // .replace("project_content.title", req.body.title)
    // .replace("project_content.owner_reference", req.body.owner_reference)
    // .replace("project_content.project_url_id", req.body.project_url_id)
    // .replace("project_content.mvp", req.body.mvp)
    // .replace("project_content.tech_used", req.body.tech_used)
    // .apply()
    // .fail(function(err){
    //   console.log("projects put failed:", err);
    //   send(err);
    // });
});

router.post("/projects", ensureAuthenticated, function(req, res, next){
console.log("post for projects ran");
  db.post('OPP_projects', {
    "active": true,
    "owner_reference": req.body.owner_reference,
    "project_content": {
      "title": req.body.title ,
      "project_url_id": req.body.project_url_id ,
      "mvp": req.body.mvp,
      "img_urls": {
        "main_img": "http://placehold.it/100x100"
      } ,
      "out_link_urls" : {
        "github_repo_url": "" ,
        "live_project_site_url": ""
      } ,
      "tech_used": req.body.tech_used
    }
  })
  .then(function (result) {
    console.log("project added");
    console.log("posted object is:", result.body.results[0].value);
    console.log("posted key is:", result.body.results[0].path.key);
    send({id:result.body.results[0].path.key, value: result.body.results[0].value});
  })
  .fail(function (err) {
    console.log("project post failed", err);
    send(err);
  });
});

router.get('/projects', function(req, res, next) {
  db.list('OPP_projects')
      .then(function (result) {
        var data = result.body.results;
        var mapped = data.map(function (element, index) {
          console.log("project: " , element.path.key);
          //console.log(element);
          /*
          console.log(element.value.project_content.project_url_id);
          console.log(element.value);
          console.log(element.value.site_project_id);
          console.log(element.value.site_project_id);
          console.log(element.value.project_content.title);
          console.log(element.value.project_content.project_url_id);
          console.log(element.value.project_content.mvp);
          console.log(element.value.project_content.tech_used);
          */
          // if(element.value.active === true){
          return {
            id: element.path.key,
            title: element.value.project_content.title ,
            project_url_id: element.value.project_content.project_url_id,
            mvp: element.value.project_content.mvp,
            tech_used: element.value.project_content.tech_used
          };
        // }
      });
        //console.log(mapped);
        res.send(mapped);
      })
      .fail(function(err){
        console.log("projects get failed:", err);
        send(err);
      });
});

router.get('/auth/github',
function(req, res, done){
  // console.log("req path", req.path);
  // console.log("req session", req.session);
  // console.log("req.query.url", req.query.url);
  console.log("query",req.query);
  req.session.returnTo = req.query.url;
  console.log("1req.session.returnTo: ", req.session.returnTo);
  done();
},
  passport.authenticate('github', { scope: [ 'user:email' ] }),
  function(req, res){
    // The req will be redirected to GitHub for authentication, so this
    // function will not be called.
});

//keep history route
router.get('/auth/github/callback', passport.authenticate('github'), function(req, res) {
  console.log("2req.session.returnTo: ", req.session.returnTo);
    var cookieValue;
    function register(){
      db.post('OPP_users', {
         "active":true,
         "github_api_data": {
           "github_id": req.user.id,
           "github_email": req.user._json.email,
           "github_display_name": req.user.displayName,
           "github_url": req.user.profileUrl,
           "github_avatar": req.user._json.avatar_url,
           "github_username": req.user.username
         } ,
         "project_reference": [] ,
         "profile_content": {
           "img_urls": {
             "profile_img": req.user._json.avatar_url ,
             "cover_photo": "" ,
             "hero_img": "" ,
             "action_shot": ""
           } ,
           "social_urls": {
             "personal": "",
             "linkedin": "",
             "twitter": ""
           } ,
           "editable_text": {
             "name": req.user.displayName,
             "title": "" ,
             "url_id": req.user.username,
             "skills": [] ,
             "tools": [] ,
             "q_and_a" : {
                 "js_tidbit": "" ,
                 "job_hope": "" ,
                 "politics": ""
             }
           } ,
           "checkbox_content" : {
             "work_status": []
           }
         }
      },false)
      .then(function(result){
        console.log("register function ran");
      })
      .fail(function(err){
          console.log("db post failed:",err);
        });
        res.cookie("url", req.user.username);
    }

    function updateInfo(key){
      console.log("update key", key);
      db.newPatchBuilder("OPP_users", key)
        .replace("github_api_data.github_id",req.user.id )
        .replace("github_api_data.github_email",req.user._json.email )
        .replace("github_api_data.github_display_name",req.user.displayName )
        .replace("github_api_data.github_url",req.user.profileUrl )
        .replace("github_api_data.github_avatar",req.user._json.avatar_url )
        .replace("github_api_data.github_username",req.user.username )
        .replace("profile_content.img_urls.profile_img",req.user._json.avatar_url )
        .replace("profile_content.editable_text.name",req.user.displayName )
        .replace("profile_content.editable_text.url_id",req.user.username )
        .apply()
      .fail(function (err) {
        console.log("patch failed");
      });
    }

    db.search('OPP_users', req.user.username)
      .then(function (result) {
        if(result.body.count>0){
          console.log("user exists");
          console.log("user object is:", result.body.results[0].value);
          cookieValue = result.body.results[0].value.profile_content.editable_text.url_id;
          console.log("key", result.body.results[0].path.key);
          updateInfo(result.body.results[0].path.key);
          res.cookie("url", cookieValue);
        }
        else{
          register();
        }
      })
      .then(function(result){
        res.cookie("logged", true);
        res.cookie("user", req.user.username);
        console.log("2cookievalue: ", cookieValue);
        res.redirect(req.session.returnTo || "/");
        req.session.returnTo = null;
      })
      .fail(function (err) {
        console.log("db search failed:", err);
      });
});

router.get('/logout', function(req, res){
  req.session.returnTo = req.query.url;
  console.log("3req.session.returnTo: ", req.session.returnTo);
  req.logout();
  res.clearCookie("logged");
  res.clearCookie("user");
  res.clearCookie("url");

  res.redirect(req.session.returnTo || "/");
  req.session.returnTo = null;
});

module.exports = router;
<commit_msg>added heroku config data to match up with config file<commit_after>var express = require('express');
var router = express.Router();
var config = (process.env.HEROKU) ? {dbkey : process.env.DBKEY, github_client_id: process.env.github_client_id, github_client_secret: process.env.github_client_secret} : require('./config.js');
var db = require('orchestrate')(config.dbkey);
var passport = require('passport');
var util = require('util');
var session = require('express-session');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var GitHubStrategy = require('passport-github2').Strategy;
var partials = require('express-partials');
var logger = require('morgan');
var cookieParser = require('cookie-parser');

//----------Github passport things----------------
var GITHUB_CLIENT_ID = config.github_client_id;
var GITHUB_CLIENT_SECRET = config.github_client_secret;

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

passport.use('github', new GitHubStrategy({
    clientID: GITHUB_CLIENT_ID,
    clientSecret: GITHUB_CLIENT_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/github/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    process.nextTick(function () {
      return done(null, profile);
    });
  }
));

router.use(passport.initialize());
router.use(passport.session());
router.use(logger('dev'));
router.use(cookieParser());

//----------------------------------------------

router.get('/', function(req, res, next) {
  if(req.user){
    console.log("cookie", req.cookies.user);
    res.render('user_session', { title: "Hello, " + req.user.displayName ,layout: 'layout', logged_user:req.cookies.url , banana:'yellow' , client_user_session: true});
  }
  else{
    console.log("!req.user");
    res.render('index', { title: 'OPP' , layout: 'layout' , banana:'red' , client_user_session: false });
  }
});

router.get('/test', function(req, res, next) {
  res.render('index', { title: 'OPP' , layout: 'tests_layout'});
});

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    // console.log("req.path: ", req.path);
    req.session.returnTo = req.path;
    return next();
  }
  else {
    console.log("ensure authentication failed");
  }
}

router.put("/profiles/:id", ensureAuthenticated, function(req, res, next){
    var id = req.params.id;

    console.log("profile updated(not really)");
    // console.log("request body", req.body);
    console.log("title:", req.body.title);
    console.log("twitter:", req.body.twitter_url);
    console.log("linkedin_url:", req.body.linkedin_url);
    console.log("personal_site_url:", req.body.personal_site_url);
    console.log("top_skills:", req.body.top_skills);
    console.log("top_tools:", req.body.top_tools);

    db.newPatchBuilder("OPP_users", id)
      .replace("profile_content.social_urls.twitter", req.body.twitter_url)
      .replace("profile_content.social_urls.linkedin", req.body.linkedin_url)
      .replace("profile_content.editable_text.title", req.body.title)
      .replace("profile_content.social_urls.personal", req.body.personal_site_url)
      .replace("profile_content.editable_text.skills", req.body.top_skills)
      .replace("profile_content.editable_text.tools", req.body.top_tools)
      .apply()
      .fail(function(err){
        console.log("profiles update failed");
        send(err);
      });
});

router.get('/profiles', function(req, res, next) {
  db.list('OPP_users')
      .then(function (result) {
        var data = result.body.results;
        var mapped = data.map(function (element, index) {
          // if(element.value.active === true){
          return {
            id: element.path.key,
            name: element.value.profile_content.editable_text.name ,
            title: element.value.profile_content.editable_text.title ,
            github_url: element.value.github_api_data.github_url ,
            profile_img_url: element.value.profile_content.img_urls.profile_img ,
            personal_site_url: element.value.profile_content.social_urls.personal ,
            linkedin_url: element.value.profile_content.social_urls.linkedin ,
            twitter_url: element.value.profile_content.social_urls.twitter ,
            url_id: element.value.profile_content.editable_text.url_id ,
            top_skills: element.value.profile_content.editable_text.skills ,
            top_tools: element.value.profile_content.editable_text.tools ,
            js_tidbit: element.value.profile_content.editable_text.q_and_a.js_tidbit ,
            work_status: element.value.profile_content.checkbox_content.work_status ,
            dream_job: element.value.profile_content.editable_text.q_and_a.job_hope
          };
        // }
      });
        // console.log("mapped: ", mapped);
        res.send(mapped);
      })
      .fail(function(err){
        console.log("profiles get failed:", err);
        send(err);
      });
});

router.put("/projects/:id", ensureAuthenticated, function(req, res, next){
    var id = req.params.id;

    console.log("project updated(not really)");
    console.log("title:", req.body.title);
    console.log("project_url_id:", req.body.project_url_id);
    console.log("mvp:", req.body.mvp);
    console.log("tech_used:", req.body.tech_used);

    // db.newPatchBuilder("OPP_projects", id)
    // .replace("project_content.title", req.body.title)
    // .replace("project_content.owner_reference", req.body.owner_reference)
    // .replace("project_content.project_url_id", req.body.project_url_id)
    // .replace("project_content.mvp", req.body.mvp)
    // .replace("project_content.tech_used", req.body.tech_used)
    // .apply()
    // .fail(function(err){
    //   console.log("projects put failed:", err);
    //   send(err);
    // });
});

router.post("/projects", ensureAuthenticated, function(req, res, next){
console.log("post for projects ran");
  db.post('OPP_projects', {
    "active": true,
    "owner_reference": req.body.owner_reference,
    "project_content": {
      "title": req.body.title ,
      "project_url_id": req.body.project_url_id ,
      "mvp": req.body.mvp,
      "img_urls": {
        "main_img": "http://placehold.it/100x100"
      } ,
      "out_link_urls" : {
        "github_repo_url": "" ,
        "live_project_site_url": ""
      } ,
      "tech_used": req.body.tech_used
    }
  })
  .then(function (result) {
    console.log("project added");
    console.log("posted object is:", result.body.results[0].value);
    console.log("posted key is:", result.body.results[0].path.key);
    send({id:result.body.results[0].path.key, value: result.body.results[0].value});
  })
  .fail(function (err) {
    console.log("project post failed", err);
    send(err);
  });
});

router.get('/projects', function(req, res, next) {
  db.list('OPP_projects')
      .then(function (result) {
        var data = result.body.results;
        var mapped = data.map(function (element, index) {
          console.log("project: " , element.path.key);
          //console.log(element);
          /*
          console.log(element.value.project_content.project_url_id);
          console.log(element.value);
          console.log(element.value.site_project_id);
          console.log(element.value.site_project_id);
          console.log(element.value.project_content.title);
          console.log(element.value.project_content.project_url_id);
          console.log(element.value.project_content.mvp);
          console.log(element.value.project_content.tech_used);
          */
          // if(element.value.active === true){
          return {
            id: element.path.key,
            title: element.value.project_content.title ,
            project_url_id: element.value.project_content.project_url_id,
            mvp: element.value.project_content.mvp,
            tech_used: element.value.project_content.tech_used
          };
        // }
      });
        //console.log(mapped);
        res.send(mapped);
      })
      .fail(function(err){
        console.log("projects get failed:", err);
        send(err);
      });
});

router.get('/auth/github',
function(req, res, done){
  // console.log("req path", req.path);
  // console.log("req session", req.session);
  // console.log("req.query.url", req.query.url);
  console.log("query",req.query);
  req.session.returnTo = req.query.url;
  console.log("1req.session.returnTo: ", req.session.returnTo);
  done();
},
  passport.authenticate('github', { scope: [ 'user:email' ] }),
  function(req, res){
    // The req will be redirected to GitHub for authentication, so this
    // function will not be called.
});

//keep history route
router.get('/auth/github/callback', passport.authenticate('github'), function(req, res) {
  console.log("2req.session.returnTo: ", req.session.returnTo);
    var cookieValue;
    function register(){
      db.post('OPP_users', {
         "active":true,
         "github_api_data": {
           "github_id": req.user.id,
           "github_email": req.user._json.email,
           "github_display_name": req.user.displayName,
           "github_url": req.user.profileUrl,
           "github_avatar": req.user._json.avatar_url,
           "github_username": req.user.username
         } ,
         "project_reference": [] ,
         "profile_content": {
           "img_urls": {
             "profile_img": req.user._json.avatar_url ,
             "cover_photo": "" ,
             "hero_img": "" ,
             "action_shot": ""
           } ,
           "social_urls": {
             "personal": "",
             "linkedin": "",
             "twitter": ""
           } ,
           "editable_text": {
             "name": req.user.displayName,
             "title": "" ,
             "url_id": req.user.username,
             "skills": [] ,
             "tools": [] ,
             "q_and_a" : {
                 "js_tidbit": "" ,
                 "job_hope": "" ,
                 "politics": ""
             }
           } ,
           "checkbox_content" : {
             "work_status": []
           }
         }
      },false)
      .then(function(result){
        console.log("register function ran");
      })
      .fail(function(err){
          console.log("db post failed:",err);
        });
        res.cookie("url", req.user.username);
    }

    function updateInfo(key){
      console.log("update key", key);
      db.newPatchBuilder("OPP_users", key)
        .replace("github_api_data.github_id",req.user.id )
        .replace("github_api_data.github_email",req.user._json.email )
        .replace("github_api_data.github_display_name",req.user.displayName )
        .replace("github_api_data.github_url",req.user.profileUrl )
        .replace("github_api_data.github_avatar",req.user._json.avatar_url )
        .replace("github_api_data.github_username",req.user.username )
        .replace("profile_content.img_urls.profile_img",req.user._json.avatar_url )
        .replace("profile_content.editable_text.name",req.user.displayName )
        .replace("profile_content.editable_text.url_id",req.user.username )
        .apply()
      .fail(function (err) {
        console.log("patch failed");
      });
    }

    db.search('OPP_users', req.user.username)
      .then(function (result) {
        if(result.body.count>0){
          console.log("user exists");
          console.log("user object is:", result.body.results[0].value);
          cookieValue = result.body.results[0].value.profile_content.editable_text.url_id;
          console.log("key", result.body.results[0].path.key);
          updateInfo(result.body.results[0].path.key);
          res.cookie("url", cookieValue);
        }
        else{
          register();
        }
      })
      .then(function(result){
        res.cookie("logged", true);
        res.cookie("user", req.user.username);
        console.log("2cookievalue: ", cookieValue);
        res.redirect(req.session.returnTo || "/");
        req.session.returnTo = null;
      })
      .fail(function (err) {
        console.log("db search failed:", err);
      });
});

router.get('/logout', function(req, res){
  req.session.returnTo = req.query.url;
  console.log("3req.session.returnTo: ", req.session.returnTo);
  req.logout();
  res.clearCookie("logged");
  res.clearCookie("user");
  res.clearCookie("url");

  res.redirect(req.session.returnTo || "/");
  req.session.returnTo = null;
});

module.exports = router;
<|endoftext|>


<commit_before>//=require "materialize/jquery.easing.1.3"
//=require "materialize/velocity.min"
//=require "materialize/hammer.min"
//=require "materialize/jquery.hammer"
//=require "lodash"

//=require "materialize/global"

//=require "materialize/collapsible"
//=require "materialize/dropdown"
//=require "materialize/leanModal"
//=require "materialize/materialbox"
//=require "materialize/parallax"
//=require "materialize/tabs"
//=require "materialize/tooltip"
//=require "materialize/waves"
//=require "materialize/toasts"
//=require "materialize/sideNav"
//=require "materialize/scrollspy"
//=require "materialize/forms"
//=require "materialize/slider"
//=require "materialize/date_picker/picker"
//=require "materialize/date_picker/picker.date"
//=require "materialize/pushpin"

//= require_self
//= require "mtl/configuration"
//= require "mtl/hooks"
//= require "mtl/clickables"
//= require "mtl/collapsible"
//= require "mtl/dropdown"
//= require "mtl/modal"
//= require "mtl/select"
//= require "mtl/toc"
//= require "mtl/icon"

// Export
window.MTL = {}
<commit_msg>include files in manifest<commit_after>//=require "materialize/jquery.easing.1.3"
//=require "materialize/velocity.min"
//=require "materialize/hammer.min"
//=require "materialize/jquery.hammer"
//=require "lodash"

//=require "materialize/global"

//=require "materialize/collapsible"
//=require "materialize/dropdown"
//=require "materialize/leanModal"
//=require "materialize/materialbox"
//=require "materialize/parallax"
//=require "materialize/tabs"
//=require "materialize/tooltip"
//=require "materialize/waves"
//=require "materialize/toasts"
//=require "materialize/sideNav"
//=require "materialize/scrollspy"
//=require "materialize/forms"
//=require "materialize/slider"
//=require "materialize/date_picker/picker"
//=require "materialize/date_picker/picker.date"
//=require "materialize/pushpin"

//= require_self
//= require "mtl/configuration"
//= require "mtl/templates"
//= require "mtl/hooks"
//= require "mtl/clickables"
//= require "mtl/collapsible"
//= require "mtl/dropdown"
//= require "mtl/modal"
//= require "mtl/select"
//= require "mtl/toc"
//= require "mtl/icon"
//= require "mtl/document_modal"

// Export
window.MTL = {}
<|endoftext|>


<commit_before>const express = require('express');
const StorageHandler = require('../lib/storage-handler');
const router = express.Router();
const storageHandler = new StorageHandler();

const REPO_KEY = 'REPOSITORIES';
const WIKI_KEY = 'WIKI_EDITS';

/* GET home page. */
router.get('/', (req, res, next) => {
  const repos = storageHandler.getStorageItem(REPO_KEY).sort((a, b) => {
    return new Date(b.created_at) - new Date(a.created_at);
  }).slice(0, 100);;

  const updatedRepos = storageHandler.getStorageItem(REPO_KEY).sort((a, b) => {
    return new Date(b.updated_at) - new Date(a.updated_at);
  }).slice(0, 100);

  const wikiEdits = storageHandler.getStorageItem(WIKI_KEY);

  res.render('index', {
    title: 'What is happening inside Mozilla?',
    repos,
    updatedRepos,
    wikiEdits
  });
});

module.exports = router;
<commit_msg>Increase number of updated repos<commit_after>const express = require('express');
const StorageHandler = require('../lib/storage-handler');
const router = express.Router();
const storageHandler = new StorageHandler();

const REPO_KEY = 'REPOSITORIES';
const WIKI_KEY = 'WIKI_EDITS';
const MAX_RETURN_ROWS_NEW = 200;
const MAX_RETURN_ROWS_UPDATED = 200;

/* GET home page. */
router.get('/', (req, res, next) => {
  const repos = storageHandler.getStorageItem(REPO_KEY).sort((a, b) => {
    return new Date(b.created_at) - new Date(a.created_at);
  }).slice(0, MAX_RETURN_ROWS_NEW);;

  const updatedRepos = storageHandler.getStorageItem(REPO_KEY).sort((a, b) => {
    return new Date(b.updated_at) - new Date(a.updated_at);
  }).slice(0, MAX_RETURN_ROWS_UPDATED);

  const wikiEdits = storageHandler.getStorageItem(WIKI_KEY);

  res.render('index', {
    title: 'What is happening inside Mozilla?',
    repos,
    updatedRepos,
    wikiEdits
  });
});

module.exports = router;
<|endoftext|>