<commit_before>var express = require('express');
var passport = require('passport');
var path = require('path');
var mongoose = require('mongoose');
var serverController = require('./server/controller.js');
var constants = require('./constants');
var GitHubStrategy = require('passport-github').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

//connect to mongodb
mongoose.connect(constants.mongodbUrl);

// Use the GithubStrategy within Passport.
passport.use(new GitHubStrategy({
	clientID: constants.githubClientId,
	clientSecret: constants.githubClientSecret,
	callbackURL: constants.passportCallbackUrl
},
function(accessToken, refreshToken, profile, cb) {
	var userJson = profile._json;
	serverController.pushUser({
		githubId: userJson.id,
		username: userJson.login,
		name: userJson.name,
		email: userJson.email,
		gravatar: userJson.avatar_url
	}, cb, profile);
}));

// Use the GoogleStrategy within Passport.
passport.use(new GoogleStrategy({
	clientID: constants.googleClientId,
	clientSecret: constants.googleClientSecret,
	callbackURL: constants.googleCallbackUrl
},
function(accessToken, refreshToken, profile, cb) {
	var userJson = profile._json;
	console.log(userJson);
	serverController.pushUser({
		githubId: '',
		username: userJson.displayName.split(' ').join(''),
		name: userJson.displayName,
		email: userJson.emails[0].value,
		gravatar: userJson.image.url
	}, cb, profile);
}
));

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

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

// Create a new Express application.
var app = express();

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({
	extended: true
}));
app.use(require('express-session')({
	secret: 'keyboard cat',
	cookie: {
		maxAge: 86400000
	},
	resave: true,
	saveUninitialized: true
}));

// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());

// Define routes.
app.get('/desktop', function(req, res) {
	res.render('desktop', {});
});

app.get('/login', serverController.checkForDesktop, function(req, res) {
	res.render('login', {
		user: req.user
	});
});

app.get('/final', serverController.checkForDesktop, function(req, res) {
	res.render('final', {});
});

app.get('/login/github', passport.authenticate('github'));

app.get('/login/google',passport.authenticate('google', {
	scope: ['profile', 'email']
}));

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

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

//Server static build files
app.use(express.static('build'));
app.use('/assets',express.static('src/assets'));

app.get('/leaderboard', serverController.checkForDesktop, function(req, res) {
	serverController.showLeaderBoard(req, res);
});

//Makes sure that user is logged in for all routes
app.use(require('connect-ensure-login').ensureLoggedIn());

app.get('/', serverController.checkForDesktop, function(req, res) {
	res.render('home', {
		user: req.user,
		words: serverController.wordlist
	});
});

//Ajax submit endpoint
app.post('/submit', function(req, res){
	//Add data to the object and push to db then send 200 ok
	if(req.user) {
		var obj = {
			user: req.user.username || req.user.displayName,
			wA: serverController.decrypt(req.body.eWA, serverController.cypher()),
			wS: serverController.decrypt(req.body.eWS, serverController.cypher()),
			sT: req.body.sT,
			eT: req.body.eT
		};
		serverController.submitScore(obj);
		res.send({});
	} else {
		res.redirect('/login');
	}
});

app.listen(3000);
console.log("Application running on port 3000");
<commit_msg>Final page after game shows only if session active<commit_after>var express = require('express');
var passport = require('passport');
var path = require('path');
var mongoose = require('mongoose');
var serverController = require('./server/controller.js');
var constants = require('./constants');
var GitHubStrategy = require('passport-github').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

//connect to mongodb
mongoose.connect(constants.mongodbUrl);

// Use the GithubStrategy within Passport.
passport.use(new GitHubStrategy({
	clientID: constants.githubClientId,
	clientSecret: constants.githubClientSecret,
	callbackURL: constants.passportCallbackUrl
},
function(accessToken, refreshToken, profile, cb) {
	var userJson = profile._json;
	serverController.pushUser({
		githubId: userJson.id,
		username: userJson.login,
		name: userJson.name,
		email: userJson.email,
		gravatar: userJson.avatar_url
	}, cb, profile);
}));

// Use the GoogleStrategy within Passport.
passport.use(new GoogleStrategy({
	clientID: constants.googleClientId,
	clientSecret: constants.googleClientSecret,
	callbackURL: constants.googleCallbackUrl
},
function(accessToken, refreshToken, profile, cb) {
	var userJson = profile._json;
	console.log(userJson);
	serverController.pushUser({
		githubId: '',
		username: userJson.displayName.split(' ').join(''),
		name: userJson.displayName,
		email: userJson.emails[0].value,
		gravatar: userJson.image.url
	}, cb, profile);
}
));

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

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

// Create a new Express application.
var app = express();

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({
	extended: true
}));
app.use(require('express-session')({
	secret: 'keyboard cat',
	cookie: {
		maxAge: 86400000
	},
	resave: true,
	saveUninitialized: true
}));

// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());

// Define routes.
app.get('/desktop', function(req, res) {
	res.render('desktop', {});
});

app.get('/login', serverController.checkForDesktop, function(req, res) {
	res.render('login', {
		user: req.user
	});
});

app.get('/login/github', passport.authenticate('github'));

app.get('/login/google',passport.authenticate('google', {
	scope: ['profile', 'email']
}));

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

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

//Server static build files
app.use(express.static('build'));
app.use('/assets',express.static('src/assets'));

app.get('/leaderboard', serverController.checkForDesktop, function(req, res) {
	serverController.showLeaderBoard(req, res);
});

//Makes sure that user is logged in for all routes
app.use(require('connect-ensure-login').ensureLoggedIn());

app.get('/', serverController.checkForDesktop, function(req, res) {
	res.render('home', {
		user: req.user,
		words: serverController.wordlist
	});
});

app.get('/final', serverController.checkForDesktop, function(req, res) {
	res.render('final', {});
});

//Ajax submit endpoint
app.post('/submit', function(req, res){
	//Add data to the object and push to db then send 200 ok
	if(req.user) {
		var obj = {
			user: req.user.username || req.user.displayName,
			wA: serverController.decrypt(req.body.eWA, serverController.cypher()),
			wS: serverController.decrypt(req.body.eWS, serverController.cypher()),
			sT: req.body.sT,
			eT: req.body.eT
		};
		serverController.submitScore(obj);
		res.send({});
	} else {
		res.redirect('/login');
	}
});

app.listen(3000);
console.log("Application running on port 3000");
<|endoftext|>


<commit_before>var http = require('http');
var https = require('https');
var fs = require('fs');
var path = require('path');

var express = require('express');
var file = require('file');
var less = require('less');
var reload = require('reload');
var Q = require('q');

var mlf = require('./MyLoLFantasy/app.js');

try {
  console.log('Rendering LESS files');

  file.walkSync(path.join(__dirname, 'less'), function(dirPath, dirs, files) {
    for (var i = 0; i < files.length; i++) {
      var filePath = path.join(dirPath, files[i]);
      less.render(fs.readFileSync(filePath).toString('utf8'), {
        paths: [path.join(__dirname, 'less')],
        filename: filePath,
        compress: false
      }, function(err, output) {
        if (err) {
          throw err;
        }

        var outFileName = path.join(__dirname, 'public/css', path.basename(files[i], '.less') + '.css');
        fs.writeFileSync(outFileName, output.css);
      });
    }
  });

  console.log('Starting server up');

  var settings = {};
  settings = _.assign(settings, require(path.join(__dirname, 'defaults.json')), require(path.join(__dirname, 'settings.json')));

  Q.Promise(function(resolve, reject, notify) {
    if (settings.dont_host_mlf) {
      resolve();
    } else {
      resolve(mlf.createApp(true));
    }
  }).then(function(mlfApp) {
    var app = express();

    if (mlfApp) {
      app.use('/MLF', mlfApp);
      console.log('Hosting MLF');
    } else {
      console.log('Opted out of hosting MLF');
    }

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

    var httpsServer = https.createServer({
      key: fs.readFileSync(path.join(__dirname, 'certs/key.pem')),
      cert: fs.readFileSync(path.join(__dirname, 'certs/key-cert.pem'))
    }, app);

    reload(httpsServer, app);

    app.get('*', function(req, res) {
      console.log(req.method + ' request at ' + req.url);
      res.sendFile('index.html', {
        root: __dirname + '/'
      });
    });

    httpsServer.listen(443, function() {
      var host = httpsServer.address().address;
      var port = httpsServer.address().port;

      console.log('Server listening at http://%s:%s', host, port);
    });

    var redirectApp = express();
    var httpServer = http.createServer(redirectApp);

    reload(httpServer, app);
    redirectApp.get('/MLF', function(req, res) {
      res.redirect('https://' + req.hostname + req.url);
    });
    redirectApp.use('/', app);

    httpServer.listen(80);

  }).fail(function(err) {
    if (err.stack) {
      console.error(err.stack);
    } else {
      console.error('Error: ' + err);
    }
  }).done();
} catch (err) {
  if (err.stack) {
    console.error(err.stack);
  } else {
    console.error('Error: ' + err);
  }
}

<commit_msg>Fixed my goof-up from my last commit<commit_after>var http = require('http');
var https = require('https');
var fs = require('fs');
var path = require('path');

var express = require('express');
var file = require('file');
var less = require('less');
var reload = require('reload');
var Q = require('q');
var _ = require('lodash');

var mlf = require('./MyLoLFantasy/app.js');

try {
  console.log('Rendering LESS files');

  file.walkSync(path.join(__dirname, 'less'), function(dirPath, dirs, files) {
    for (var i = 0; i < files.length; i++) {
      var filePath = path.join(dirPath, files[i]);
      less.render(fs.readFileSync(filePath).toString('utf8'), {
        paths: [path.join(__dirname, 'less')],
        filename: filePath,
        compress: false
      }, function(err, output) {
        if (err) {
          throw err;
        }

        var outFileName = path.join(__dirname, 'public/css', path.basename(files[i], '.less') + '.css');
        fs.writeFileSync(outFileName, output.css);
      });
    }
  });

  console.log('Starting server up');

  var settings = {};
  settings = _.assign(settings, require(path.join(__dirname, 'defaults.json')), require(path.join(__dirname, 'settings.json')));

  Q.Promise(function(resolve, reject, notify) {
    if (settings.dont_host_mlf) {
      resolve();
    } else {
      resolve(mlf.createApp(true));
    }
  }).then(function(mlfApp) {
    var app = express();

    if (mlfApp) {
      app.use('/MLF', mlfApp);
      console.log('Hosting MLF');
    } else {
      console.log('Opted out of hosting MLF');
    }

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

    var httpsServer = https.createServer({
      key: fs.readFileSync(path.join(__dirname, 'certs/key.pem')),
      cert: fs.readFileSync(path.join(__dirname, 'certs/key-cert.pem'))
    }, app);

    reload(httpsServer, app);

    app.get('*', function(req, res) {
      console.log(req.method + ' request at ' + req.url);
      res.sendFile('index.html', {
        root: __dirname + '/'
      });
    });

    httpsServer.listen(443, function() {
      var host = httpsServer.address().address;
      var port = httpsServer.address().port;

      console.log('Server listening at http://%s:%s', host, port);
    });

    var redirectApp = express();
    var httpServer = http.createServer(redirectApp);

    reload(httpServer, app);
    redirectApp.get('/MLF', function(req, res) {
      res.redirect('https://' + req.hostname + req.url);
    });
    redirectApp.use('/', app);

    httpServer.listen(80);

  }).fail(function(err) {
    if (err.stack) {
      console.error(err.stack);
    } else {
      console.error('Error: ' + err);
    }
  }).done();
} catch (err) {
  if (err.stack) {
    console.error(err.stack);
  } else {
    console.error('Error: ' + err);
  }
}

<|endoftext|>


<commit_before>/**
 * Module dependencies
*/
var express  = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');
var http = require('http');
var path = path = require('path');
var uuid = require('node-uuid');

var vhost = 'acomanda.local'
var port     = process.env.PORT || 3000;
var ip     = process.env.IP || "localhost";

var app = express();

var connection = require('./config/database')(mongoose);
var models = require('./models/models')(connection);
require('./config/passport')(passport,models); // pass passport for configuration

app.configure(function() {
    // set up our express application
    app.set('port', port);
    app.use(express.logger('dev')); // log every request to the console
    app.use(express.cookieParser()); // read cookies (needed for auth)
    app.use(express.bodyParser()); // get information from html forms
    app.set('view engine', 'html'); // set up html for templating
    app.engine('.html', require('ejs').__express);
    app.set('views', __dirname + '/views');
    app.use(express.static(path.join(__dirname, 'public')));
    //app.use(express.session({ secret: 'keyboard cat' }));// persistent login sessions
    app.use(express.methodOverride());
    app.use(express.json());
    app.use(express.urlencoded());
    //app.use(flash()); // use connect-flash for flash messages stored in session

    //passport configuration
    app.use(passport.initialize());
    app.use(passport.session());// persistent login sessions
    //provagg
    app.use(app.router); //init routing

});

require('./app/routes.js')(app, passport,models); // load our routes and pass in our app and fully configured passport

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

// production only
if (app.get('env') === 'production') {
    // TODO
};

//express.vhost(vhost, app);

var server = http.createServer(app).listen(app.get('port'), function () {
    console.log('Express server listening on port ' + vhost+":"+server.address().port);
});<commit_msg>remove database config<commit_after>/**
 * Module dependencies
*/
var express  = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');
var http = require('http');
var path = path = require('path');
var uuid = require('node-uuid');

var vhost = 'acomanda.local'
var port     = process.env.PORT || 3000;
var ip     = process.env.IP || "localhost";

var app = express();

if (app.get('env') === 'development') {
    var uri_local = require('../database_local'); // not used, usage config/database.js
    process.env.MONGOLAB_URI = uri_local;
};

var connection = require('./config/database')(mongoose);
var models = require('./models/models')(connection);
require('./config/passport')(passport,models); // pass passport for configuration

app.configure(function() {
    // set up our express application
    app.set('port', port);
    app.use(express.logger('dev')); // log every request to the console
    app.use(express.cookieParser()); // read cookies (needed for auth)
    app.use(express.bodyParser()); // get information from html forms
    app.set('view engine', 'html'); // set up html for templating
    app.engine('.html', require('ejs').__express);
    app.set('views', __dirname + '/views');
    app.use(express.static(path.join(__dirname, 'public')));
    //app.use(express.session({ secret: 'keyboard cat' }));// persistent login sessions
    app.use(express.methodOverride());
    app.use(express.json());
    app.use(express.urlencoded());
    //app.use(flash()); // use connect-flash for flash messages stored in session

    //passport configuration
    app.use(passport.initialize());
    app.use(passport.session());// persistent login sessions
    //provagg
    app.use(app.router); //init routing

});

require('./app/routes.js')(app, passport,models); // load our routes and pass in our app and fully configured passport

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

// production only
if (app.get('env') === 'production') {
    // TODO
};

//express.vhost(vhost, app);

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


<commit_before>import Settings from 'services/settings'

const OS 	 = require('opensubtitles-api')
const http = require('http')
const fs 	 = require('fs')

const OpenSubtitles = new OS({
  useragent: 'EasysubsNJ',
  ssl: true,
})

function get(id, filename, fpath, filesize) {
  return OpenSubtitles.search({
    sublanguageid: 'eng',
    path: fpath,
    filename,
    filesize,
    extensions: ['srt'],
  })
  .then(sub => {
    const hasUrl = Object.keys(sub).length
    sub.file = { id, name, path: fpath, hasUrl }
    return sub
  })
}

function getName(videoName) {
  const n = videoName.lastIndexOf('.')
  const videoNameWithoutExtension = n > -1 ? videoName.substr(0, n) : videoName
  const subExt = Settings.get().subExtension.value
  console.log(`${videoNameWithoutExtension}.${subExt}`);
  return `${videoNameWithoutExtension}.${subExt}`
}

function download(id, url, name) {
  // TODO: check if url is duplicated. Sometimes
	// OpenSubtitles is returning wrong sub in a TV Show
  const file = fs.createWriteStream(name)
  return new Promise(resolve => {
    http.get(url, response => {
      response.pipe(file)
      resolve('ready')
    })
  })
}

export default {
  get,
  getName,
  download,
}
<commit_msg>get subtitles using saved settings<commit_after>import Settings from 'services/settings'

const OS 	 = require('opensubtitles-api')
const http = require('http')
const fs 	 = require('fs')

const OpenSubtitles = new OS({
  useragent: 'EasysubsNJ',
  ssl: true,
})

function get(id, filename, fpath, filesize) {
  const settings = Settings.get()
  return OpenSubtitles.search({
    sublanguageid: settings.subLanguage.value,
    path: fpath,
    filename,
    filesize,
    extensions: [settings.subExtension.value],
  })
  .then(sub => {
    const hasUrl = Object.keys(sub).length
    sub.file = { id, name, path: fpath, hasUrl }
    return sub
  })
}

function getName(videoName) {
  const n = videoName.lastIndexOf('.')
  const videoNameWithoutExtension = n > -1 ? videoName.substr(0, n) : videoName
  const subExt = Settings.get().subExtension.value
  return `${videoNameWithoutExtension}.${subExt}`
}

function download(id, url, name) {
  // TODO: check if url is duplicated. Sometimes
	// OpenSubtitles is returning wrong sub in a TV Show
  const file = fs.createWriteStream(name)
  return new Promise(resolve => {
    http.get(url, response => {
      response.pipe(file)
      resolve('ready')
    })
  })
}

export default {
  get,
  getName,
  download,
}
<|endoftext|>


<commit_before>'use strict';

var Node = require('../node');
var debug = require('../../util/debug')('analysis:georeference-street-address');

var TYPE = 'georeference-street-address';
var PARAMS = {
    source: Node.PARAM.NODE(Node.GEOMETRY.ANY),
    street_address_column: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    street_address_template: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    city: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    city_column: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    state: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    state_column: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    country: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    country_column: Node.PARAM.NULLABLE(Node.PARAM.STRING())
};

var GeoreferenceStreetAddress = Node.create(TYPE, PARAMS, { cache: true,
    beforeCreate: function() {
        if (this.street_address_column === null && this.street_address_template === null) {
            throw new Error('Either `street_address_column` or `street_address_template` params must be provided');
        }
    }
});

module.exports = GeoreferenceStreetAddress;

GeoreferenceStreetAddress.prototype.sql = function() {
    var sql = queryTemplate({
        source: this.source.getQuery(),
        columns: this.source.getColumns(true).join(', '),
        country_column: this.getFunctionParam('country'),
        state_column: this.getFunctionParam('state'),
        city_column: this.getFunctionParam('city'),
        street_column: this.getStreetAddressColumnParam(),
        params: this.getGeocoderParams().join(', ')
    });

    debug(sql);

    return sql;
};

GeoreferenceStreetAddress.prototype.getGeocoderParams = function () {
    var geocoderParams = [
        this.getStreetAddressColumnParam(),
        this.getFunctionParam('city'),
        this.getFunctionParam('state'),
        this.getFunctionParam('country')
    ];

    return geocoderParams;
};

var COLUMNS_TEMPLATE_REGEX = /\{\{([^\}]*)\}\}|([^{]+)/g;
GeoreferenceStreetAddress.prototype.getStreetAddressColumnParam = function() {
    if (this.street_address_column) {
        return this.getFunctionParam('street_address');
    }

    // Let's split columns and literals to escape literals and concat everything. Example:
    // "{{c1}} {{c2}}, {{c3}}, Spain" --> ["c1", "c2", "', '", "c3", "', Spain'"]
    var columnsAndLiterals = [];
    var addressMatch;
    while ((addressMatch = COLUMNS_TEMPLATE_REGEX.exec(this.street_address_template)) !== null) {
        var column = addressMatch[1];
        if(column) {
            columnsAndLiterals.push(column.trim());
        } else {
            columnsAndLiterals.push(`'${addressMatch[0]}'`);
        }
    }

    if (columnsAndLiterals.length === 0) {
        return `$tpl$'${this.street_address_template}'$tpl$`;
    }

    return `$tpl$${columnsAndLiterals.join(' || ')}$tpl$`;
};

GeoreferenceStreetAddress.prototype.getFunctionParam = function (name) {
    if (this[name + '_column']) {
        return `'${this[name + '_column']}'`;
    }

    if (this[name]) {
        return `'''${this[name]}'''`;
    }

    return 'NULL';
};

var queryTemplate = Node.template(
    `
    SELECT
       {{=it.columns}},
       _y.the_geom, st_transform(st_setsrid(_y.the_geom, 4326), 3857) as the_geom_webmercator, _y.metadata
    FROM
       ({{=it.source}}) _x
       LEFT JOIN
       (SELECT * from
           cdb_dataservices_client.cdb_bulk_geocode_street_point(
                   'select * from ({{=it.source}}) __x',
                   {{=it.street_column}},
                   {{=it.city_column}},
                   {{=it.state_column}},
                   {{=it.country_column}}
           )) _y
       USING (cartodb_id)
       `);
<commit_msg>Relevance metadata<commit_after>'use strict';

var Node = require('../node');
var debug = require('../../util/debug')('analysis:georeference-street-address');

var TYPE = 'georeference-street-address';
var PARAMS = {
    source: Node.PARAM.NODE(Node.GEOMETRY.ANY),
    street_address_column: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    street_address_template: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    city: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    city_column: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    state: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    state_column: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    country: Node.PARAM.NULLABLE(Node.PARAM.STRING()),
    country_column: Node.PARAM.NULLABLE(Node.PARAM.STRING())
};

var GeoreferenceStreetAddress = Node.create(TYPE, PARAMS, { cache: true,
    beforeCreate: function() {
        if (this.street_address_column === null && this.street_address_template === null) {
            throw new Error('Either `street_address_column` or `street_address_template` params must be provided');
        }
    }
});

module.exports = GeoreferenceStreetAddress;

GeoreferenceStreetAddress.prototype.sql = function() {
    var sql = queryTemplate({
        source: this.source.getQuery(),
        columns: this.source.getColumns(true).join(', '),
        country_column: this.getFunctionParam('country'),
        state_column: this.getFunctionParam('state'),
        city_column: this.getFunctionParam('city'),
        street_column: this.getStreetAddressColumnParam(),
        params: this.getGeocoderParams().join(', ')
    });

    debug(sql);

    return sql;
};

GeoreferenceStreetAddress.prototype.getGeocoderParams = function () {
    var geocoderParams = [
        this.getStreetAddressColumnParam(),
        this.getFunctionParam('city'),
        this.getFunctionParam('state'),
        this.getFunctionParam('country')
    ];

    return geocoderParams;
};

var COLUMNS_TEMPLATE_REGEX = /\{\{([^\}]*)\}\}|([^{]+)/g;
GeoreferenceStreetAddress.prototype.getStreetAddressColumnParam = function() {
    if (this.street_address_column) {
        return this.getFunctionParam('street_address');
    }

    // Let's split columns and literals to escape literals and concat everything. Example:
    // "{{c1}} {{c2}}, {{c3}}, Spain" --> ["c1", "c2", "', '", "c3", "', Spain'"]
    var columnsAndLiterals = [];
    var addressMatch;
    while ((addressMatch = COLUMNS_TEMPLATE_REGEX.exec(this.street_address_template)) !== null) {
        var column = addressMatch[1];
        if(column) {
            columnsAndLiterals.push(column.trim());
        } else {
            columnsAndLiterals.push(`'${addressMatch[0]}'`);
        }
    }

    if (columnsAndLiterals.length === 0) {
        return `$tpl$'${this.street_address_template}'$tpl$`;
    }

    return `$tpl$${columnsAndLiterals.join(' || ')}$tpl$`;
};

GeoreferenceStreetAddress.prototype.getFunctionParam = function (name) {
    if (this[name + '_column']) {
        return `'${this[name + '_column']}'`;
    }

    if (this[name]) {
        return `'''${this[name]}'''`;
    }

    return 'NULL';
};

var queryTemplate = Node.template(
    `
    SELECT
       {{=it.columns}},
       _y.the_geom, st_transform(st_setsrid(_y.the_geom, 4326), 3857) as the_geom_webmercator,
       _y.__geocoding_meta_relevance
    FROM
       ({{=it.source}}) _x
       LEFT JOIN
       (SELECT cartodb_id, the_geom, metadata->'relevance' as __geocoding_meta_relevance
        FROM
           cdb_dataservices_client.cdb_bulk_geocode_street_point(
                   'select * from ({{=it.source}}) __x',
                   {{=it.street_column}},
                   {{=it.city_column}},
                   {{=it.state_column}},
                   {{=it.country_column}}
           )) _y
       USING (cartodb_id)
       `);
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import DataContainerBase from '../containers/DataContainerBase'
import Starships from './index'

export default class StarshipsContainer extends DataContainerBase {

  constructor() {
    super()
    this.state = {
      data: {}
    }
    this.fetch_details = {
      url: 'https://swapi.co/api/starships/',
      options: { method: 'get' }
    }
  }

  results_parser = response => {
    try {
      return JSON.parse(response._bodyText).results
    }
    catch (err) {
      console.log('results parser error - - - - - - - - - - -', err)
    }
  }

  results_assigner = results => {
    this.setState({
      data: results
    })
  }

  render() {
    return <Starships data={this.state.data} navigate={this.props.navigate} />
  }

}<commit_msg>refactored starships<commit_after>import React, { Component } from 'react'
import DC_HOC from '../containers/DataContainerHOC'
import Starships from './index'

class StarshipsContainer extends Component {

  fetch_details = {
    url: 'https://swapi.co/api/starships/',
    options: { method: 'get' }
  }

  render() {
    return <Starships data={this.state.data} navigate={this.props.navigate} />
  }

}

export default DC_HOC(StarshipsContainer)<|endoftext|>


<commit_before>'use strict';

let Promise = require('bluebird');
let mailService = require('./mailService');
let offersService = require('./offersService');
let companyService = require('./companyService');
let templateService = require('./templateService');

let adapters = [
  // require('../adapters/km'),
  // require('../adapters/weisenburger'),
  // require('../adapters/cuffaro'),
  // require('../adapters/throm'),
  // require('../adapters/kassel'),
  // require('../adapters/artekt'),
  require('../adapters/goebelbecker'),
  // require('../adapters/helblerichter'),
  // require('../adapters/volkswohnung'),
  // require('../adapters/immoka'),
  // require('../adapters/spaka'),
  // require('../adapters/spaka_haeuser'),
  // require('../adapters/weststadtmakler'),
  // require('../adapters/immotrend'),
  // require('../adapters/gebaka'),
  // require('../adapters/gig'),
  // require('../adapters/besserwohnen'),
  // require('../adapters/haitz'),
  // require('../adapters/suw'),
  // require('../adapters/laub'),
  // require('../adapters/blumenwinkel'),
  // require('../adapters/neubaukompass'),
  // require('../adapters/baar'),
  // require('../adapters/ewg'),
  // require('../adapters/forum'),
  // require('../adapters/wipfler'),
  // require('../adapters/sekundus'),
  // require('../adapters/speck'),
  // require('../adapters/leitgieb'),
  // require('../adapters/engelvoelkers'),
  // require('../adapters/seegerrusswurm'),
  // require('../adapters/ebaykleinanzeigen'),
  // require('../adapters/heck'),
  // require('../adapters/immowenk'),
  // require('../adapters/aniseustachi'),
];

module.exports.scrapeAll = () => {
  return Promise.map(adapters, adapter => adapter.scrape())
    .then(flatResponses => {
      return Promise.map(flatResponses, flats => {
        return Promise.map(flats, checkOfferExists);
      });
    })
    .then(flatResponses => {
      return Promise.map(flatResponses, flats => {
        return Promise.map(flats, insertIfNew);
      });
    })
    .then(flatResponses => {
      console.log('Scraping done');

      if (hasNewEntries(flatResponses)) {
        companyService.getCompanies()
          .then(companies => {
            let emptyEntries = getEmptyEntries(flatResponses);
            let companyNames = getCompanyNames(companies);
            let data = {
              flatResponses,
              companyNames,
              emptyEntries
            };
            let text = templateService.compileTemplate(templateService.TEMPLATE_NAMES.OFFERS, data);

            mailService.sendMail(
              'Flatfinder found new offers',
              text
            );
          });
      } else {
        console.log('No new entries');
      }
    })
    .catch(error => {
      mailService.sendMail(
        'Flatfinder had a hickup',
        JSON.stringify(error.stack)
      );

      throw error;
    });
}

function checkOfferExists(flat) {
  return offersService.offerExists(flat.companyId, flat.title, flat.url)
    .then(offerExists => {
      flat.exists = offerExists;
      return flat;
    });
}

function insertIfNew(flat) {
  if (flat.exists) {
    return flat;
  }
  return offersService.insertOffer(flat.companyId, flat.title, flat.url)
    .then(() => flat);
}

function getEmptyEntries(flatResponses) {
  let emptyEntries = 0;
  for (let flats of flatResponses) {
    if (flats.length === 0) {
      emptyEntries += 1;
    }
  }
  return emptyEntries;
}

function hasNewEntries(flatResponses) {
  for (let flats of flatResponses) {
    for (let flat of flats) {
      if (!flat.exists) {
        return true;
      }
    }
  }
  return false;
}

function getCompanyNames(companies) {
  let companyNames = {};
  for (let comp of companies) {
    companyNames[comp.id] = comp.name;
  }
  return companyNames;
}<commit_msg>simple<commit_after>'use strict';

let Promise = require('bluebird');
let mailService = require('./mailService');
let offersService = require('./offersService');
let companyService = require('./companyService');
let templateService = require('./templateService');

let adapters = [
  // require('../adapters/km'),
  // require('../adapters/weisenburger'),
  // require('../adapters/cuffaro'),
  // require('../adapters/throm'),
  // require('../adapters/kassel'),
  // require('../adapters/artekt'),
  // require('../adapters/goebelbecker'),
  // require('../adapters/helblerichter'),
  // require('../adapters/volkswohnung'),
  // require('../adapters/immoka'),
  // require('../adapters/spaka'),
  // require('../adapters/spaka_haeuser'),
  // require('../adapters/weststadtmakler'),
  // require('../adapters/immotrend'),
  // require('../adapters/gebaka'),
  // require('../adapters/gig'),
  // require('../adapters/besserwohnen'),
  // require('../adapters/haitz'),
  // require('../adapters/suw'),
  // require('../adapters/laub'),
  // require('../adapters/blumenwinkel'),
  // require('../adapters/neubaukompass'),
  // require('../adapters/baar'),
  // require('../adapters/ewg'),
  // require('../adapters/forum'),
  // require('../adapters/wipfler'),
  require('../adapters/sekundus'),
  // require('../adapters/speck'),
  // require('../adapters/leitgieb'),
  // require('../adapters/engelvoelkers'),
  // require('../adapters/seegerrusswurm'),
  // require('../adapters/ebaykleinanzeigen'),
  // require('../adapters/heck'),
  // require('../adapters/immowenk'),
  // require('../adapters/aniseustachi'),
];

module.exports.scrapeAll = () => {
  return Promise.map(adapters, adapter => adapter.scrape())
    .then(flatResponses => {
      return Promise.map(flatResponses, flats => {
        return Promise.map(flats, checkOfferExists);
      });
    })
    .then(flatResponses => {
      return Promise.map(flatResponses, flats => {
        return Promise.map(flats, insertIfNew);
      });
    })
    .then(flatResponses => {
      console.log('Scraping done');

      if (hasNewEntries(flatResponses)) {
        companyService.getCompanies()
          .then(companies => {
            let emptyEntries = getEmptyEntries(flatResponses);
            let companyNames = getCompanyNames(companies);
            let data = {
              flatResponses,
              companyNames,
              emptyEntries
            };
            let text = templateService.compileTemplate(templateService.TEMPLATE_NAMES.OFFERS, data);

            mailService.sendMail(
              'Flatfinder found new offers',
              text
            );
          });
      } else {
        console.log('No new entries');
      }
    })
    .catch(error => {
      mailService.sendMail(
        'Flatfinder had a hickup',
        JSON.stringify(error.stack)
      );

      throw error;
    });
}

function checkOfferExists(flat) {
  return offersService.offerExists(flat.companyId, flat.title, flat.url)
    .then(offerExists => {
      flat.exists = offerExists;
      return flat;
    });
}

function insertIfNew(flat) {
  if (flat.exists) {
    return flat;
  }
  return offersService.insertOffer(flat.companyId, flat.title, flat.url)
    .then(() => flat);
}

function getEmptyEntries(flatResponses) {
  let emptyEntries = 0;
  for (let flats of flatResponses) {
    if (flats.length === 0) {
      emptyEntries += 1;
    }
  }
  return emptyEntries;
}

function hasNewEntries(flatResponses) {
  for (let flats of flatResponses) {
    for (let flat of flats) {
      if (!flat.exists) {
        return true;
      }
    }
  }
  return false;
}

function getCompanyNames(companies) {
  let companyNames = {};
  for (let comp of companies) {
    companyNames[comp.id] = comp.name;
  }
  return companyNames;
}<|endoftext|>


<commit_before>'use strict'
var Emitter = require('../../../emitter')
var Base = require('../../../base')
var setKey = Base.prototype.setKey

module.exports = new Emitter({
  emitInstances: false,
  secondary: true,
  properties: {
    pattern: new Base({
      properties: {
        $condition: true
      },
      define: {
        setKey (key, val, event, nocontext, escape) {
          if (key === 'parent') {
            key = '$parent'
          }
          return setKey.call(this, key, val, event, nocontext, escape)
        }
      },
      ChildConstructor: 'Constructor'
    })
  },
  inject: [
    require('../run'),
    require('../field'),
    require('../object'),
    require('../upward'),
    require('../findemit'),
    require('../condition')
  ],
  define: {
    generateConstructor () {
      return function derivedBase (val, event, parent, key) {
        Base.apply(this, arguments)
        if (parent && !parent[key]) {
          this.subField(false, void 0, parent.parent, this.pattern, 0, true, {})
        }
      }
    }
  }
}).Constructor
<commit_msg>pattern is now an observable<commit_after>'use strict'
var Emitter = require('../../../emitter')
var Base = require('../../../base')

var LightObservable = new Base({
  inject: [
    require('../../constructor'),
    require('../../on'),
    require('../../emit'),
    require('../../off'),
    require('../../remove'),
    require('../../set')
  ]
}).Constructor

var setKey = LightObservable.prototype.setKey

module.exports = new Emitter({
  emitInstances: false,
  secondary: true,
  properties: {
    pattern: new LightObservable({
      define: {
        setKey (key, val, event, nocontext, escape) {
          if (key === 'parent') {
            key = '$parent'
          }
          return setKey.call(this, key, val, event, nocontext, escape)
        }
      },
      ChildConstructor: 'Constructor'
    })
  },
  inject: [
    require('../run'),
    require('../field'),
    require('../object'),
    require('../upward'),
    require('../findemit'),
    require('../condition')
  ],
  define: {
    generateConstructor () {
      return function derivedBase (val, event, parent, key) {
        Base.apply(this, arguments)
        if (parent && !parent[key]) {
          this.subField(false, void 0, parent.parent, this.pattern, 0, true, {})
        }
      }
    }
  }
}).Constructor
<|endoftext|>


<commit_before>/**
 * Created by Joshua on 8/15/2015.
 */

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

//app.set('port', (process.env.PORT || 8085))

app.use(express.static(__dirname + '/client'));

app.get('/', function(request, response) {
    response.render('/client/index.html')
});

app.listen('8081','0.0.0.0', function(){
    console.log('Listening on port 8081');
});<commit_msg>Fixing port so it'll work with Cloud9<commit_after>/**
 * Created by Joshua on 8/15/2015.
 */

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

//app.set('port', (process.env.PORT || 8085))

app.use(express.static(__dirname + '/client'));

app.get('/', function(request, response) {
    response.render('/client/index.html')
});

app.listen('8080','0.0.0.0', function(){
    console.log('Listening on port 8080');
});<|endoftext|>


<commit_before>'use strict'; // jshint node: true, browser: false, esnext:true

var express = require('express');
var proxy   = require('http-proxy').createProxyServer({});
var app     = express();

var version = (process.env.VERSION || String(new Date().getTime()/10000-145430280|0)).substr(0, 7); // 1234567
var cookieParser = require('cookie-parser')

proxy.on('error', function () { }); // ignore proxy errors

// Http calls debug
app.use(require('morgan')('dev'));
app.use(cookieParser());

// SET ROUTES

app.use('/app/libs', express.static(__dirname + '/app/libs', { setHeaders: setCustomCacheControl }));
app.use('/app',      express.static(__dirname + '/app'     , { setHeaders: setCustomCacheControl }));
app.use('/',         express.static(__dirname + '/public'  , { setHeaders: setCustomCacheControl }));
app.get('/app/*', (req, res) => res.status(404).send("404 - Not Found"));

app.all('/api/*', (req, res) => proxy.web(req, res, { target: 'https://api.cbddev.xyz', changeOrigin: true }));
///non angularjs file for activating email
app.get('/activate', (req, res) => res.sendFile(__dirname + '/app/views/activate.html'));

// SET TEMPLATE

app.get('/*', (req, res) => {
	res.setHeader('Cache-Control', 'public, max-age=0');
	res.cookie('VERSION', version);
	res.sendFile(__dirname + '/app/template.html');
});

// START HTTP SERVER

app.listen(process.env.PORT || 8000, function () {
	console.info(`Server listening on ${this.address().port}`);
});

process.on('SIGTERM', ()=>process.exit());

//============================================================
//
//
//============================================================
function setCustomCacheControl(res, path) {

	var versionWrong = false;
	var versionMatch = false;

	versionWrong |= res.req.query.v && res.req.query.v!=version;
	versionWrong |= res.req.cookies.VERSION && res.req.cookies.VERSION!=version;
	versionMatch |= res.req.query.v && res.req.query.v==version;
	versionMatch |= res.req.cookies.VERSION && res.req.cookies.VERSION==version;

	if(versionWrong || !versionMatch)
		return res.setHeader('Cache-Control', 'public, max-age=0');

	res.setHeader('Cache-Control', 'public, max-age=86400000');
}
<commit_msg>Refactoring<commit_after>'use strict'; // jshint node: true, browser: false, esnext:true

var express      = require('express');
var cookieParser = require('cookie-parser')
var morgan       = require('morgan');
var proxy        = require('http-proxy').createProxyServer({});

proxy.on('error', function () { }); // ignore proxy errors

// CREATER ADD & ADD MIDDLEWARES

var app = express();
app.use(cookieParser());
app.use(morgan('dev'));

var version = (process.env.VERSION || String(new Date().getTime()/10000-145430280|0)).substr(0, 7); // 1234567

// SET ROUTES

app.use('/app/libs', express.static(__dirname + '/app/libs', { setHeaders: setCustomCacheControl }));
app.use('/app',      express.static(__dirname + '/app'     , { setHeaders: setCustomCacheControl }));
app.use('/',         express.static(__dirname + '/public'  , { setHeaders: setCustomCacheControl }));
app.get('/app/*', (req, res) => res.status(404).send("404 - Not Found"));

app.all('/api/*', (req, res) => proxy.web(req, res, { target: 'https://api.cbddev.xyz', changeOrigin: true }));
///non angularjs file for activating email
app.get('/activate', (req, res) => res.sendFile(__dirname + '/app/views/activate.html'));

// SET TEMPLATE

app.get('/*', (req, res) => {
	res.setHeader('Cache-Control', 'public, max-age=0');
	res.cookie('VERSION', version);
	res.sendFile(__dirname + '/app/template.html');
});

// START HTTP SERVER

app.listen(process.env.PORT || 8000, function () {
	console.info(`Server listening on ${this.address().port}`);
});

process.on('SIGTERM', ()=>process.exit());

//============================================================
//
//
//============================================================
function setCustomCacheControl(res, path) {

	var versionWrong = false;
	var versionMatch = false;

	versionWrong |= res.req.query.v && res.req.query.v!=version;
	versionWrong |= res.req.cookies.VERSION && res.req.cookies.VERSION!=version;
	versionMatch |= res.req.query.v && res.req.query.v==version;
	versionMatch |= res.req.cookies.VERSION && res.req.cookies.VERSION==version;

	if(versionWrong || !versionMatch)
		return res.setHeader('Cache-Control', 'public, max-age=0');

	res.setHeader('Cache-Control', 'public, max-age=86400000');
}
<|endoftext|>


<commit_before>"use strict";
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('exit', function (worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
        cluster.fork();
    });
} else {
    var db_driver = "./databases/";
    if (process.env.vsaa_dbms) {
        db_driver += process.env.vsaa_dbms;
    }
    else {
        db_driver += "mssql";
    }

    global.db = require(db_driver); // This is a bit of a hack and outdated way of doing things...

    var restify = require("restify");
    var restifyOAuth2 = require("restify-oauth2");
    var hooks = require("./hooks");

    var server = restify.createServer({
        name: "Very Simple Application Analytics Server",
        version: "0.0.2",
        formatters: {
            "application/hal+json": function (req, res, body) {
                return res.formatters["application/json"](req, res, body);
            }
        }
    });

    var RESOURCES = Object.freeze({
        INITIAL: "/",
        TOKEN: "/login",
        EVENT: "/event"
    });

    server.use(restify.authorizationParser());
    server.use(restify.bodyParser({ mapParams: false }));
    restifyOAuth2.cc(server, { tokenEndpoint: RESOURCES.TOKEN, hooks: hooks });

    server.get(RESOURCES.INITIAL, function (req, res) {
        var response = {
            _links: {
                self: { href: RESOURCES.INITIAL }
            }
        };

        if (req.clientId) {
            response._links["http://rel.example.com/event"] = { href: RESOURCES.EVENT };
        } else {
            response._links["oauth2-token"] = {
                href: RESOURCES.TOKEN,
                "grant-types": "client_credentials",
                "token-types": "bearer"
            };
        }

        res.contentType = "application/hal+json";
        res.send(response);
    });

    server.post(RESOURCES.EVENT, function (req, res) {
        if (!req.clientId) {
            return res.sendUnauthenticated();
        }
        var fields = [
            req.body.DeviceId,
            req.body.Description,
            req.body.ApiKey
        ];
        var response = {
            "success": "event recorded successfully",
            _links: {
                self: { href: RESOURCES.EVENT },
                parent: { href: RESOURCES.INITIAL }
            }
        }
        db.createEvent(fields, function (err, result) {
            if (err) {
                response = {
                    "error": "err",
                    _links: {
                        self: { href: RESOURCES.EVENT },
                        parent: { href: RESOURCES.INITIAL }
                    }
                }
            }
        });
        if (req.body.message_type === 'APPLICATION_EVENT_QUIT')
            hooks.invalidateClientToken(req.authorization.credentials);
        res.contentType = "application/hal+json";
        res.send(response);
    });

    // Adding error information...

    process.on('uncaughtException', function (err) {
        console.log("UNCAUGHT EXCEPTION ");
        console.log("[Inside 'uncaughtException' event] " + err.stack || err.message);
    });

    server.listen(8080);
}<commit_msg>Refactoring<commit_after>"use strict";

// Database driver selection

var db_driver = "./databases/";
if (process.env.vsaa_dbms) {
	db_driver += process.env.vsaa_dbms;
}
else {
    db_driver += "mysql";
}

// Required node modules
var restify = require("restify");
var restifyOAuth2 = require("restify-oauth2");
var cluster = require('cluster');

// Process variables

global.db = require(db_driver); // This is a bit of a hack and outdated way of doing things...

var numCPUs = require('os').cpus().length;
var port = 8080; // Default port to listen

if (process.argc >= 2) {
	port = parseInt(process.argv[2]); // Port can be also passed as an argument
}

var hooks = require("./hooks");
var server = restify.createServer({
	name: "Very Simple Application Analytics Server",
	version: "0.0.3",
	formatters: {
		"application/hal+json": function (req, res, body) {
			return res.formatters["application/json"](req, res, body);
		}
	}
});

var RESOURCES = Object.freeze({
	INITIAL: "/",
	TOKEN: "/login",
	EVENT: "/event"
});

server.use(restify.authorizationParser());
server.use(restify.bodyParser({ mapParams: false }));
	restifyOAuth2.cc(server, { tokenEndpoint: RESOURCES.TOKEN, hooks: hooks });
server.get(RESOURCES.INITIAL, function (req, res) {
	var response = {
		_links: {
			self: { href: RESOURCES.INITIAL }
		}
	};

	if (req.clientId) {
		response._links["http://rel.example.com/event"] = { href: RESOURCES.EVENT };
	} else {
		response._links["oauth2-token"] = {
			href: RESOURCES.TOKEN,
			"grant-types": "client_credentials",
			"token-types": "bearer"
		};
	}

	res.contentType = "application/hal+json";
	res.send(response);
});

server.post(RESOURCES.EVENT, function (req, res) {
	if (!req.clientId) {
		return res.sendUnauthenticated();
	}
	var fields = [
		req.body.DeviceId,
		req.body.Description,
		req.body.ApiKey
	];
	var response = {
		"success": "event recorded successfully",
		_links: {
			self: { href: RESOURCES.EVENT },
			parent: { href: RESOURCES.INITIAL }
		}
	}
	db.createEvent(fields, function (err, result) {
		if (err) {
			response = {
				"error": "err",
				_links: {
					self: { href: RESOURCES.EVENT },
					parent: { href: RESOURCES.INITIAL }
				}
			}
		}
	});
	if (req.body.message_type === 'APPLICATION_EVENT_QUIT')
		hooks.invalidateClientToken(req.authorization.credentials);
	res.contentType = "application/hal+json";
	res.send(response);
});

// Adding error information...
process.on('uncaughtException', function (err) {
	console.log("UNCAUGHT EXCEPTION ");
	console.log("[Inside 'uncaughtException' event] " + err.stack || err.message);
});

// Clustering to utilize all CPU cores
if (cluster.isMaster) {

    // Fork workers, one for each CPU.
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('exit', function (worker, code, signal) {
    	console.log('worker ' + worker.process.pid + ' died');
    	cluster.fork();
    });
}
else {
    server.listen(port);
}<|endoftext|>


<commit_before>//
// NavBreadCrumbListItem component
//
class NavBreadCrumbListItem extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      activePhase: null,
      disabled: null
    };

    this.handleBreadCrumbClick = this.handleBreadCrumbClick.bind(this);
  }

  handleBreadCrumbClick(targetPhase, e) {
    let self = this;
    let activePhase = this.state.activePhase;
    let app = this.props.app;

    // TODO!!!
    // this.props.navbar.setState({
    //   targetPhase: targetPhase
    // }, function() {
    //   // If the phase transition doesn't need to be confirmed
    //   if(!(activePhase >= app.state.constants.APP_PHASE_COMMIT_OPEN &&
    //       targetPhase < app.state.constants.APP_PHASE_COMMIT_OPEN)) {
    //     // Switch to the targetPhase
    //     app.setState({
    //       phase: targetPhase
    //     });
    //   }
    //   else {
    //     // Do nothing: Confirmation modal will take the control
    //   }
    // });
  }

  componentDidMount() {
    this.setState({
      activePhase: this.props.activePhase,
      disabled: this.props.phase > this.state.activePhase ? true : false
    });
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      activePhase: nextProps.activePhase,
      disabled: nextProps.phase > nextProps.activePhase ? true : false
    });
  }

  render() {
    let active = this.props.phase == this.state.activePhase ? 'active' : '';
    let className = active + ' ' + (this.state.disabled ? 'disabled' : '');

    return (

          {this.props.label}

    );
  }
}

export default NavBreadCrumbListItem;
<commit_msg>resolve merge conflicts: after rebase<commit_after>//
// NavBreadCrumbListItem component
//
class NavBreadCrumbListItem extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      activePhase: null,
      disabled: null
    };

    this.handleBreadCrumbClick = this.handleBreadCrumbClick.bind(this);
  }

  handleBreadCrumbClick(targetPhase, e) {
    let self = this;
    let activePhase = this.state.activePhase;
    let app = this.props.app;

    // TODO!!!
    // this.props.navbar.setState({
    //   targetPhase: targetPhase
    // }, function() {
    //   // If the phase transition doesn't need to be confirmed
    //   if(!(activePhase >= app.state.constants.APP_PHASE_COMMIT_OPEN &&
    //       targetPhase < app.state.constants.APP_PHASE_COMMIT_OPEN)) {
    //     // Switch to the targetPhase
    //     app.setState({
    //       phase: targetPhase
    //     });
    //   }
    //   else {
    //     // Do nothing: Confirmation modal will take the control
    //   }
    // });
  }

  componentDidMount() {
    this.setState({
      activePhase: this.props.activePhase,
      disabled: this.props.phase > this.state.activePhase ? true : false
    });
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      activePhase: nextProps.activePhase,
      disabled: nextProps.phase > nextProps.activePhase ? true : false
      disabled: nextProps.phase > nextProps.activePhase ? true: false
    });
  }

  render() {
    let active = this.props.phase == this.state.activePhase ? 'active' : '';
    let className = active + ' ' + (this.state.disabled ? 'disabled' : '');

    return (

          {this.props.label}

    );
  }
}

export default NavBreadCrumbListItem;
<|endoftext|>


<commit_before>var express = require('express'),
    fs = require('fs'),
    cradle = require('cradle'),
    person = require('./routes/person'),
    nodeUserGid = "node",
    nodeUserUid = "node",
    apikeyMatches = false;

var app = express();
var db = new(cradle.Connection)().database('api_users');

app.use(express.compress());

//TODO: Logging of requests.
//TODO: CORS restrictions should apply to crossdomain.xml too.
//TODO: log rotation
app.use(function (req, res, next) {
    "use strict";

    var apikeyMatches = false;
    if(req.headers.origin && req.query.apikey) {
        //TODO: look up host in couchdb and only send the A-OK if it matches the origin header
        db.get(req.query.apikey, function (err, doc) {
            if (doc.host === req.headers.origin) {
                res.header('Access-Control-Allow-Origin', req.headers.origin);
                apikeyMatches = true;

                if(req.headers['access-control-request-method']) {
                    res.header('Access-Control-Allow-Methods', "GET, OPTIONS");
                }

                res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
            }

            if (req.method === 'OPTIONS') {
                res.send(200);
            } else  {
                next();
            }
        });
    } else {
        next();
    }
});

app.get(/^\/static\/([\w\/\.]+)$/, function(req,res) {
    "use strict";
    if (fs.existsSync(__dirname + '/static/' + req.params[0])) {
        res.sendfile( __dirname + '/static/' + req.params[0]);
        return;
    }
    res.send(404);
});

app.get('/person/search', person.search);

// Needed for polyfill for IE7 support :-(
app.get('/crossdomain.xml', function(req,res) {
    "use strict";
    res.send(
        '<?xml version="1.0"?>\n' +
        '<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">\n' +
        '<cross-domain-policy>\n' +
        '  <allow-access-from domain="*" />\n' +
        '  <allow-http-request-headers-from domain="*" headers="*" />\n' +
        '</cross-domain-policy>\n'
    );
});

app.listen(80, function() {
  process.setgid(nodeUserGid);
  process.setuid(nodeUserUid);
});

console.log('Listening on port 80...');<commit_msg>no sync call crutches<commit_after>var express = require('express'),
    fs = require('fs'),
    cradle = require('cradle'),
    person = require('./routes/person'),
    nodeUserGid = "node",
    nodeUserUid = "node",
    apikeyMatches = false;

var app = express();
var db = new(cradle.Connection)().database('api_users');

app.use(express.compress());

//TODO: Logging of requests.
//TODO: CORS restrictions should apply to crossdomain.xml too.
//TODO: log rotation
app.use(function (req, res, next) {
    "use strict";

    var apikeyMatches = false;
    if(req.headers.origin && req.query.apikey) {
        //TODO: look up host in couchdb and only send the A-OK if it matches the origin header
        db.get(req.query.apikey, function (err, doc) {
            if (doc.host === req.headers.origin) {
                res.header('Access-Control-Allow-Origin', req.headers.origin);
                apikeyMatches = true;

                if(req.headers['access-control-request-method']) {
                    res.header('Access-Control-Allow-Methods', "GET, OPTIONS");
                }

                res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
            }

            if (req.method === 'OPTIONS') {
                res.send(200);
            } else  {
                next();
            }
        });
    } else {
        next();
    }
});

app.get(/^\/static\/([\w\/\.]+)$/, function(req,res) {
    "use strict";
    fs.exists(__dirname + '/static/' + req.params[0], function(exists) {
        if (exists) {
            res.sendfile( __dirname + '/static/' + req.params[0]);
            return;
        } else {
            res.send(404);
        }
    });
});

app.get('/person/search', person.search);

// Needed for polyfill for IE7 support :-(
app.get('/crossdomain.xml', function(req,res) {
    "use strict";
    res.send(
        '<?xml version="1.0"?>\n' +
        '<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">\n' +
        '<cross-domain-policy>\n' +
        '  <allow-access-from domain="*" />\n' +
        '  <allow-http-request-headers-from domain="*" headers="*" />\n' +
        '</cross-domain-policy>\n'
    );
});

app.listen(80, function() {
  process.setgid(nodeUserGid);
  process.setuid(nodeUserUid);
});

console.log('Listening on port 80...');<|endoftext|>


<commit_before>var express = require("express");
var bodyParser = require("body-parser");
var pgconfig = require('./config');
var pg = require('pg');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(__dirname));

var conString = process.env.ELEPHANTSQL_URL || "postgres://awdtqouh:" + pgconfig.pgkey + "@pellefant.db.elephantsql.com:5432/awdtqouh";
///### INSTANCE WITH CONNECT AND END####///
// var client = new pg.Client(conString);
// client.connect(function(err) {
//   if(err) {
//     return console.error('could not connect to postgres', err);
//   }
// client.query(), function(err, result) {
//   if(err) {
//     return console.error('error running query', err);
//   }
//   console.log(result);
//   //output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
//   client.end();
//   });
// });

app.get('/users', function (req, res) {
  pg.connect(conString, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }
    client.query('select * from site_user', function(err, result) {
      done();

      if(err) {
        return console.error('error running query', err);
      }

      var data = result.rows;
        var mapped = data.map(function (element, index) {
          return {id: element.id, username: element.name};
        });

      res.send(mapped);
    });
  });
});
//****reference for orchestrate for app.get(/users)***//
// db.list('users')
// .then(function (result) {
//   var data = result.body.results;
//   var mapped = data.map(function (element, index) {
//     return {id: element.path.key, username: element.value.username};
//   });
//   res.send(mapped);
// });

app.get('/userTasks/:username', function (req, res) {
  var username = req.params.username;
  var id;
  var queryResults;

  pg.connect(conString, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }

    client.query('select * from site_user where name = \'' + username + '\'', function(err, result) {
      if(err) {
        return console.error('error running query1 of get', err);
      }
      console.log("query1 result.rows: ", result.rows);

      id = result.rows[0].id;
      console.log('the initial query found an id of: ', id);

      client.query('select task.id, task.title, task.description, site_user.name as creator, task.assignee, task.status into tempTable from task left join site_user on task.creator = site_user.id', function(err, result) {
        if(err) {
          return console.error('error running query2 of get', err);
        }
        console.log("query2 result.rows: ", result.rows);

        client.query('select tempTable.id, tempTable.title, tempTable.description, tempTable.creator, site_user.name as assignee, tempTable.status into tempTable2 from tempTable left join site_user on tempTable.assignee = site_user.id', function(err, result) {
          if(err) {
            return console.error('error running query3 of get', err);
          }
          console.log("query3 result.rows: ", result.rows);

          client.query('drop table tempTable', function(err, result) {
            if(err) {
              return console.error('error running query4 of get', err);
            }
            console.log("query4 result.rows: ", result.rows);

            client.query('select * from tempTable2 where (creator = \'' + username + '\' or assignee = \'' + username + '\')', function(err, result) {
              if(err) {
                return console.error('error running query5 of get', err);
              }
              console.log("query5 result.rows: ", result.rows);

              queryResults = result;

              client.query('drop table tempTable2', function(err, result) {
                if(err) {
                  return console.error('error running query6 of get', err);
                }
                console.log("query6 result.rows: ", result.rows);

                done();

                var mapped = queryResults.rows.map(function (element, index) {
                  return {id: element.id, title: element.title, description: element.description, creator: element.creator, assignee: element.assignee, status: element.status};
                });

                console.log("mapped is: ", mapped);
                res.send(mapped);
              });
            });
          });
        });
      });
    });
  });
});
//***REFERENCE TO ORCHESTRATE FOR APP.GET/userTasks*****//
// db.search('tasks', 'value.assignee:'+ username +' OR value.creator:' +username)
// .then(function (result) {
//   var data = result.body.results;
//   var mapped = data.map(function (element, index) {
//     return {id: element.path.key, title: element.value.title, description: element.value.description, creator: element.value.creator, assignee: element.value.assignee, status: element.value.status};
//   });
//   res.send(mapped);
// })
// .fail(function (err) {});

app.get('/unassignedTasks/:username', function (req, res) {
  console.log("/unassignedTasks/:username GET route initiated");
  var username = req.params.username;
  var id;
  var queryResults;

  pg.connect(conString, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }

    client.query("select task.id, task.title, task.description, site_user.name as creator, '' as assignee, task.status from task left join site_user on task.creator = site_user.id where (task.status = 'Unassigned' and site_user.name <> \'" + username + "\')", function(err, result) {
      if(err) {
        return console.error('error running query1 of get', err);
      }
      console.log("query1 result.rows: ", result.rows);

      queryResults = result;
      done();

      var mapped = queryResults.rows.map(function (element, index) {
        return {id: element.id, title: element.title, description: element.description, creator: element.creator, assignee: element.assignee, status: element.status};
      });
      res.send(mapped);
    });
  });
});
///****** PREVIOUS VERSION USING ORCHESTRATE ******///
// app.get('/unassignedTasks/:username', function (req, res) {
//   console.log("/unassignedTasks/:username GET route initiated");
//   var username = req.params.username;
//   db.search('tasks', 'value.status: "Unassigned" AND value.creator: (NOT ' + username + ')')
//   .then(function (result) {
//     console.log("db.search successful");
//     var data = result.body.results;
//     var mapped = data.map(function (element, index) {
//       return {id: element.path.key, title: element.value.title, description: element.value.description, creator: element.value.creator, assignee: element.value.assignee, status: element.value.status};
//     });
//     res.send(mapped);
//   })
//   .fail(function (err) {console.log("db.search not successful");});
// });

app.post('/users', function (req, res) {
  var id;

  pg.connect(conString, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }

    client.query('insert into site_user (name) values (\'' + req.body.username + '\')', function(err, result) {
      if(err) {
        return console.error('error running query1 of get', err);
      }
      console.log("query1 result.rows: ", result.rows);

      client.query('select max(id) from site_user', function(err, result) {
        if(err) {
          return console.error('error running query2 of get', err);
        }
        console.log("query2 result.rows: ", result.rows);

        id = result.rows[0].max;
        done();

        res.send({id: id});
      });
    });
  });
});
///****** PREVIOUS VERSION USING ORCHESTRATE ******///
//   db.list('users')
//   .then(function(result) {
//     id = result.body.count + 1;
//     // console.log(id);
//     db.put('users', id, {"username" : req.body.username})
//     .then(function(result) {
//       // console.log(req.body.username);
//       res.send({id: id});
//     });
//   });
// });

app.put('/tasks/:id', function (req, res) {
  console.log("userTasks PUT initiated");
  var id = req.params.id;
  var queryResults;

  pg.connect(conString, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }

    if(req.body.assignee !== '') {
      client.query('select id from site_user where name = \'' + req.body.assignee +'\'', function(err, result) {
        if(err) {
          return console.error('error running query1 of get', err);
        }
        console.log("query1 result.rows: ", result.rows);

        queryResults = result;

        client.query('update task set assignee = \'' + queryResults.rows[0].id + '\', status = \'' + req.body.status + '\' where id = \'' + id + '\'', function(err, result) {
          if(err) {
            return console.error('error running query2 of get', err);
          }
          console.log("query2 result.rows: ", result.rows);

          done();

          res.send({id: id});
        });
      });
    }
    else {
      client.query('update task set assignee = null, status = \'' + req.body.status + '\' where id = \'' + id + '\'', function(err, result) {
        if(err) {
          return console.error('error running query1 of get', err);
        }
        console.log("query1 result.rows: ", result.rows);

        done();

        res.send({id: id});
      });
    }
  });
});
///****** PREVIOUS VERSION USING ORCHESTRATE ******///
// db.put('tasks', id, {"title" : req.body.title, "description" : req.body.description, "creator" : req.body.creator, "assignee" : req.body.assignee, "status": req.body.status})
// .then(function(result) {
//   console.log("task update works");
//   res.send({id: id});
// });

///****** PREVIOUS VERSION USING ORCHESTRATE ******///
app.post('/tasks', function (req, res) {   // was previously set to /userTasks/:username
  console.log("userTasks POST initiated");
  var id;
  var queryResultsCreator;
  var queryResultsAssignee;

  pg.connect(conString, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }

    client.query('select id from site_user where name = \'' + req.body.creator + '\'', function(err, result) {
      if(err) {
        return console.error('error running query1 of get', err);
      }
      console.log("query1 result.rows: ", result.rows);

      queryResultsCreator = result;

      client.query('select id from site_user where name = \'' + req.body.assignee + '\'', function(err, result) {
        if(err) {
          return console.error('error running query2 of get', err);
        }
        console.log("query2 result.rows: ", result.rows);

        queryResultsAssignee = result;

        client.query('insert into task (title, description, creator, assignee, status) values (\'' + req.body.title + '\', \'' + req.body.description + '\', \'' + queryResultsCreator.rows[0].id + '\', \'' + queryResultsAssignee.rows[0].id + '\', \'' + req.body.status + '\')', function(err, result) {
          if(err) {
            return console.error('error running query3 of get', err);
          }
          console.log("query3 result.rows: ", result.rows);

          client.query('select max(id) from task', function(err, result) {
            if(err) {
              return console.error('error running query4 of get', err);
            }
            console.log("query4 result.rows: ", result.rows);

            id = result.rows[0].max;
            done();

            res.send({id: id});
          });
        });
      });
    });
  });
});
///****** PREVIOUS VERSION USING ORCHESTRATE ******/// /// BELIEVED TO BE REDUNDANT ///
// app.put('/tasks/:id', function (req, res) {
//   console.log("unassignedTasks PUT initiated");
//   var id = req.params.id;
//   db.put('tasks', id, {"title" : req.body.title, "description" : req.body.description, "creator" : req.body.creator, "assignee" : req.body.assignee, "status": req.body.status})
//   .then(function(result) {
//     console.log("task update works");
//     res.send({id: id});
//   });
// });

///****** PREVIOUS VERSION USING ORCHESTRATE ******/// /// BELIEVED TO BE REDUNDANT ///
// app.post('/unassignedTasks', function (req, res) {
//   console.log("unassignedTasks POST initiated");
//   var id;
//   db.list('tasks')
//   .then(function(result) {
//     id = result.body.count + 1;
//     db.put('tasks', id, {"title" : req.body.title, "description" : req.body.description, "creator" : req.body.creator, "assignee" : req.body.assignee, "status": req.body.status})
//     .then(function(result) {
//       console.log("task create works");
//       res.send({id: id});
//     });
//   });
// });

app.listen(3000, function () {
  console.log("Server is running...........");
});
<commit_msg>Fix post route for tasks<commit_after>var express = require("express");
var bodyParser = require("body-parser");
var pgconfig = require('./config');
var pg = require('pg');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(__dirname));

var conString = process.env.ELEPHANTSQL_URL || "postgres://awdtqouh:" + pgconfig.pgkey + "@pellefant.db.elephantsql.com:5432/awdtqouh";
///### INSTANCE WITH CONNECT AND END####///
// var client = new pg.Client(conString);
// client.connect(function(err) {
//   if(err) {
//     return console.error('could not connect to postgres', err);
//   }
// client.query(), function(err, result) {
//   if(err) {
//     return console.error('error running query', err);
//   }
//   console.log(result);
//   //output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
//   client.end();
//   });
// });

app.get('/users', function (req, res) {
  pg.connect(conString, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }
    client.query('select * from site_user', function(err, result) {
      done();

      if(err) {
        return console.error('error running query', err);
      }

      var data = result.rows;
        var mapped = data.map(function (element, index) {
          return {id: element.id, username: element.name};
        });

      res.send(mapped);
    });
  });
});
//****reference for orchestrate for app.get(/users)***//
// db.list('users')
// .then(function (result) {
//   var data = result.body.results;
//   var mapped = data.map(function (element, index) {
//     return {id: element.path.key, username: element.value.username};
//   });
//   res.send(mapped);
// });

app.get('/userTasks/:username', function (req, res) {
  var username = req.params.username;
  var id;
  var queryResults;

  pg.connect(conString, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }

    client.query('select * from site_user where name = \'' + username + '\'', function(err, result) {
      if(err) {
        return console.error('error running query1 of get', err);
      }
      console.log("query1 result.rows: ", result.rows);

      id = result.rows[0].id;
      console.log('the initial query found an id of: ', id);

      client.query('select task.id, task.title, task.description, site_user.name as creator, task.assignee, task.status into tempTable from task left join site_user on task.creator = site_user.id', function(err, result) {
        if(err) {
          return console.error('error running query2 of get', err);
        }
        console.log("query2 result.rows: ", result.rows);

        client.query('select tempTable.id, tempTable.title, tempTable.description, tempTable.creator, site_user.name as assignee, tempTable.status into tempTable2 from tempTable left join site_user on tempTable.assignee = site_user.id', function(err, result) {
          if(err) {
            return console.error('error running query3 of get', err);
          }
          console.log("query3 result.rows: ", result.rows);

          client.query('drop table tempTable', function(err, result) {
            if(err) {
              return console.error('error running query4 of get', err);
            }
            console.log("query4 result.rows: ", result.rows);

            client.query('select * from tempTable2 where (creator = \'' + username + '\' or assignee = \'' + username + '\')', function(err, result) {
              if(err) {
                return console.error('error running query5 of get', err);
              }
              console.log("query5 result.rows: ", result.rows);

              queryResults = result;

              client.query('drop table tempTable2', function(err, result) {
                if(err) {
                  return console.error('error running query6 of get', err);
                }
                console.log("query6 result.rows: ", result.rows);

                done();

                var mapped = queryResults.rows.map(function (element, index) {
                  return {id: element.id, title: element.title, description: element.description, creator: element.creator, assignee: element.assignee, status: element.status};
                });

                console.log("mapped is: ", mapped);
                res.send(mapped);
              });
            });
          });
        });
      });
    });
  });
});
//***REFERENCE TO ORCHESTRATE FOR APP.GET/userTasks*****//
// db.search('tasks', 'value.assignee:'+ username +' OR value.creator:' +username)
// .then(function (result) {
//   var data = result.body.results;
//   var mapped = data.map(function (element, index) {
//     return {id: element.path.key, title: element.value.title, description: element.value.description, creator: element.value.creator, assignee: element.value.assignee, status: element.value.status};
//   });
//   res.send(mapped);
// })
// .fail(function (err) {});

app.get('/unassignedTasks/:username', function (req, res) {
  console.log("/unassignedTasks/:username GET route initiated");
  var username = req.params.username;
  var id;
  var queryResults;

  pg.connect(conString, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }

    client.query("select task.id, task.title, task.description, site_user.name as creator, '' as assignee, task.status from task left join site_user on task.creator = site_user.id where (task.status = 'Unassigned' and site_user.name <> \'" + username + "\')", function(err, result) {
      if(err) {
        return console.error('error running query1 of get', err);
      }
      console.log("query1 result.rows: ", result.rows);

      queryResults = result;
      done();

      var mapped = queryResults.rows.map(function (element, index) {
        return {id: element.id, title: element.title, description: element.description, creator: element.creator, assignee: element.assignee, status: element.status};
      });
      res.send(mapped);
    });
  });
});
///****** PREVIOUS VERSION USING ORCHESTRATE ******///
// app.get('/unassignedTasks/:username', function (req, res) {
//   console.log("/unassignedTasks/:username GET route initiated");
//   var username = req.params.username;
//   db.search('tasks', 'value.status: "Unassigned" AND value.creator: (NOT ' + username + ')')
//   .then(function (result) {
//     console.log("db.search successful");
//     var data = result.body.results;
//     var mapped = data.map(function (element, index) {
//       return {id: element.path.key, title: element.value.title, description: element.value.description, creator: element.value.creator, assignee: element.value.assignee, status: element.value.status};
//     });
//     res.send(mapped);
//   })
//   .fail(function (err) {console.log("db.search not successful");});
// });

app.post('/users', function (req, res) {
  var id;

  pg.connect(conString, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }

    client.query('insert into site_user (name) values (\'' + req.body.username + '\')', function(err, result) {
      if(err) {
        return console.error('error running query1 of get', err);
      }
      console.log("query1 result.rows: ", result.rows);

      client.query('select max(id) from site_user', function(err, result) {
        if(err) {
          return console.error('error running query2 of get', err);
        }
        console.log("query2 result.rows: ", result.rows);

        id = result.rows[0].max;
        done();

        res.send({id: id});
      });
    });
  });
});
///****** PREVIOUS VERSION USING ORCHESTRATE ******///
//   db.list('users')
//   .then(function(result) {
//     id = result.body.count + 1;
//     // console.log(id);
//     db.put('users', id, {"username" : req.body.username})
//     .then(function(result) {
//       // console.log(req.body.username);
//       res.send({id: id});
//     });
//   });
// });

app.put('/tasks/:id', function (req, res) {
  console.log("userTasks PUT initiated");
  var id = req.params.id;
  var queryResults;

  pg.connect(conString, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }

    if(req.body.assignee !== '') {
      client.query('select id from site_user where name = \'' + req.body.assignee +'\'', function(err, result) {
        if(err) {
          return console.error('error running query1 of get', err);
        }
        console.log("query1 result.rows: ", result.rows);

        queryResults = result;

        client.query('update task set assignee = \'' + queryResults.rows[0].id + '\', status = \'' + req.body.status + '\' where id = \'' + id + '\'', function(err, result) {
          if(err) {
            return console.error('error running query2 of get', err);
          }
          console.log("query2 result.rows: ", result.rows);

          done();

          res.send({id: id});
        });
      });
    }
    else {
      client.query('update task set assignee = null, status = \'' + req.body.status + '\' where id = \'' + id + '\'', function(err, result) {
        if(err) {
          return console.error('error running query1 of get', err);
        }
        console.log("query1 result.rows: ", result.rows);

        done();

        res.send({id: id});
      });
    }
  });
});
///****** PREVIOUS VERSION USING ORCHESTRATE ******///
// db.put('tasks', id, {"title" : req.body.title, "description" : req.body.description, "creator" : req.body.creator, "assignee" : req.body.assignee, "status": req.body.status})
// .then(function(result) {
//   console.log("task update works");
//   res.send({id: id});
// });

///****** PREVIOUS VERSION USING ORCHESTRATE ******///
app.post('/tasks', function (req, res) {   // was previously set to /userTasks/:username
  console.log("userTasks POST initiated");
  var id;
  var queryResultsCreator;
  var queryResultsAssignee;

  pg.connect(conString, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }

    client.query('select id from site_user where name = \'' + req.body.creator + '\'', function(err, result) {
      if(err) {
        return console.error('error running query1 of get', err);
      }
      console.log("query1 result.rows: ", result.rows);

      queryResultsCreator = result;

      if(req.body.assignee !== '') {
        client.query('select id from site_user where name = \'' + req.body.assignee + '\'', function(err, result) {
          if(err) {
            return console.error('error running query2 of get', err);
          }
          console.log("query2 result.rows: ", result.rows);

          queryResultsAssignee = result;

          client.query('insert into task (title, description, creator, assignee, status) values (\'' + req.body.title + '\', \'' + req.body.description + '\', \'' + queryResultsCreator.rows[0].id + '\', \'' + queryResultsAssignee.rows[0].id + '\', \'' + req.body.status + '\')', function(err, result) {
            if(err) {
              return console.error('error running query3 of get', err);
            }
            console.log("query3 result.rows: ", result.rows);

            client.query('select max(id) from task', function(err, result) {
              if(err) {
                return console.error('error running query4 of get', err);
              }
              console.log("query4 result.rows: ", result.rows);

              id = result.rows[0].max;
              done();

              res.send({id: id});
            });
          });
        });
      }
      else {
        client.query('insert into task (title, description, creator, assignee, status) values (\'' + req.body.title + '\', \'' + req.body.description + '\', \'' + queryResultsCreator.rows[0].id + '\', null, \'' + req.body.status + '\')', function(err, result) {
          if(err) {
            return console.error('error running query2 of get', err);
          }
          console.log("query2 result.rows: ", result.rows);

          queryResultsAssignee = result;

          client.query('select max(id) from task', function(err, result) {
            if(err) {
              return console.error('error running query3 of get', err);
            }
            console.log("query3 result.rows: ", result.rows);

            id = result.rows[0].max;
            done();

            res.send({id: id});
          });
        });
      }
    });
  });
});
///****** PREVIOUS VERSION USING ORCHESTRATE ******/// /// BELIEVED TO BE REDUNDANT ///
// app.put('/tasks/:id', function (req, res) {
//   console.log("unassignedTasks PUT initiated");
//   var id = req.params.id;
//   db.put('tasks', id, {"title" : req.body.title, "description" : req.body.description, "creator" : req.body.creator, "assignee" : req.body.assignee, "status": req.body.status})
//   .then(function(result) {
//     console.log("task update works");
//     res.send({id: id});
//   });
// });

///****** PREVIOUS VERSION USING ORCHESTRATE ******/// /// BELIEVED TO BE REDUNDANT ///
// app.post('/unassignedTasks', function (req, res) {
//   console.log("unassignedTasks POST initiated");
//   var id;
//   db.list('tasks')
//   .then(function(result) {
//     id = result.body.count + 1;
//     db.put('tasks', id, {"title" : req.body.title, "description" : req.body.description, "creator" : req.body.creator, "assignee" : req.body.assignee, "status": req.body.status})
//     .then(function(result) {
//       console.log("task create works");
//       res.send({id: id});
//     });
//   });
// });

app.listen(3000, function () {
  console.log("Server is running...........");
});
<|endoftext|>