<commit_before>var passport = require('passport')
  , mongoose = require('mongoose')
  , _ = require('underscore')
  , fs = require('fs');

var User = mongoose.model('User')
  , Project = mongoose.model('Project');

module.exports = function(app) {

  app.get('/api/projects', loadProjects, render('projects'));

  app.post('/api/projects/create', isAuth, validateProject, saveProject, gracefulRes);

  app.get('/api/projects/remove/:project_id', isAuth, isProjectLeader, removeProject, gracefulRes);

  app.get('/api/projects/create', isAuth, setViewVar('statuses', app.get('statuses')), render('new_project'));

  app.post('/api/cover', isAuth, uploadCover);

  app.get('/api/projects/edit/:project_id', isAuth, setViewVar('statuses', app.get('statuses')), isProjectLeader, loadProject, render('edit'));

  app.post('/api/projects/edit/:project_id', isAuth, isProjectLeader, validateProject, updateProject, gracefulRes);

  app.get('/api/projects/join/:project_id', isAuth, joinProject, followProject, loadProject, gracefulRes); 

  app.get('/api/projects/leave/:project_id', isAuth, isProjectMember, leaveProject, loadProject, gracefulRes); 

  app.get('/api/projects/follow/:project_id', isAuth, followProject, loadProject, gracefulRes); 

  app.get('/api/projects/unfollow/:project_id', isAuth, isProjectFollower, unfollowProject, loadProject, gracefulRes); 

  app.get('/api/p/:project_id', loadProject, render('project_full'));

  app.get('/api/search', loadSearchProjects, render('projects'));

};


/*
 * Render templates
 */
var render = function(path) {
  return function(req, res) { 
    res.render(path, function(err, html){
      if(err) return res.send(500);
      res.json({html: html});
    });
  };
};


/*
 * Render jade view
 */
var renderView = function(path) {
  return function(req, res) {
    res.render(path);
  };
};


/*
 * Redirect to a route
 */

var redirect = function(route) {
  return function(req, res) {
    res.redirect(route);
  };
};

/*
 * Add current user template variable
 */

var loadUser = function(req, res, next) {
  res.locals.user = req.user;
  next();
};

/*
 * Makes vars available to views
 */

var setViewVar = function(key, value) {
  return function(req, res, next) {
    res.locals[key] = value;
    next();
  };
};  

/*
 * Load app providers
 */

var loadProviders = function(req, res, next) {
  res.locals.providers = req.app.get('providers');
  next();
};


/*
 * Check if current user is authenticated
 */

var isAuth = function(req, res, next){
  (req.isAuthenticated()) ? next() : res.send(403);
};

/*
 * Check if current user is project leader
 */

var isProjectLeader = function(req, res, next){
  Project.findOne({ _id: req.params.project_id }, function(err, project) {
    if (err || !project) return res.send(404);
    if (!req.user.is_admin && req.user.id != project.leader) return res.send(401);
    req.project = project;
    next();
  });
};

/*
 * Load all projects
 */

var loadProjects = function(req, res, next) {
  Project.find({})
  .populate('contributors')
  .populate('followers')
  .populate('leader')
  .exec(function(err, projects) {
    if(err) return res.send(500);
    res.locals.projects = projects;
    res.locals.user = req.user;
    res.locals.userExists = userExistsInArray;
    next();
  });
};

/*
 * Load specific project
 */

var loadProject = function(req, res, next) {
  Project.findById(req.params.project_id)
  .populate('contributors')
  .populate('followers')
  .populate('leader')
  .exec(function(err, project) {
    if(err || !project) return res.send(500);
    res.locals.project = project;
    res.locals.user = req.user;
    res.locals.userExists = userExistsInArray;
    next();
  });
};

var userExistsInArray = function(user, arr){
  return _.find(arr, function(u){
    return (u.id == user.id);
  });
};

/*
 * Load searched projects
 * TODO: use mongoose plugin for keywords
 */

var loadSearchProjects = function(req, res, next) {
  var regex = new RegExp(req.query.q, 'i');
  var query = {};

  if(!req.query.q.length) return res.redirect('/api/projects');

  if(req.query.type === "title") query['title'] = regex;
  else if(req.query.type === "tag") query['tags'] = regex;
  else return res.send(500);

  Project
  .find(query, function(err, projects) {
    if(err) return res.send(500);
    res.locals.projects = projects;
    res.locals.user = req.user;
    res.locals.userExists = userExistsInArray;
    next();
  });
};

/*
 * Check project fields
 */

var validateProject = function(req, res, next) {console.log(req.body);
  if(req.body.title && req.body.description) next();
  else res.send(500, "Project Title and Description fields must be complete.");
};

/*
 * Save new project
 */

var saveProject = function(req, res, next) {<commit_msg>added backend function for issue #27<commit_after>var passport = require('passport')
  , mongoose = require('mongoose')
  , _ = require('underscore')
  , fs = require('fs')
  , request = require('superagent');

var User = mongoose.model('User')
  , Project = mongoose.model('Project');

module.exports = function(app) {

  app.get('/api/projects', loadProjects, render('projects'));

  app.post('/api/projects/create', isAuth, isGithubRepo, validateProject, saveProject, gracefulRes);

  app.get('/api/projects/remove/:project_id', isAuth, isProjectLeader, removeProject, gracefulRes);

  app.get('/api/projects/create', isAuth, setViewVar('statuses', app.get('statuses')), render('new_project'));

  app.post('/api/cover', isAuth, uploadCover);

  app.get('/api/projects/edit/:project_id', isAuth, setViewVar('statuses', app.get('statuses')), isProjectLeader, loadProject, render('edit'));

  app.post('/api/projects/edit/:project_id', isAuth, isProjectLeader, validateProject, updateProject, gracefulRes);

  app.get('/api/projects/join/:project_id', isAuth, joinProject, followProject, loadProject, gracefulRes); 

  app.get('/api/projects/leave/:project_id', isAuth, isProjectMember, leaveProject, loadProject, gracefulRes); 

  app.get('/api/projects/follow/:project_id', isAuth, followProject, loadProject, gracefulRes); 

  app.get('/api/projects/unfollow/:project_id', isAuth, isProjectFollower, unfollowProject, loadProject, gracefulRes); 

  app.get('/api/p/:project_id', loadProject, render('project_full'));

  app.get('/api/search', loadSearchProjects, render('projects'));

};


/*
 * Render templates
 */
var render = function(path) {
  return function(req, res) { 
    res.render(path, function(err, html){
      if(err) return res.send(500);
      res.json({html: html});
    });
  };
};


/*
 * Render jade view
 */
var renderView = function(path) {
  return function(req, res) {
    res.render(path);
  };
};


/*
 * Redirect to a route
 */

var redirect = function(route) {
  return function(req, res) {
    res.redirect(route);
  };
};

/*
 * Add current user template variable
 */

var loadUser = function(req, res, next) {
  res.locals.user = req.user;
  next();
};

/*
 * Makes vars available to views
 */

var setViewVar = function(key, value) {
  return function(req, res, next) {
    res.locals[key] = value;
    next();
  };
};  

/*
 * Load app providers
 */

var loadProviders = function(req, res, next) {
  res.locals.providers = req.app.get('providers');
  next();
};


/*
 * Check if current user is authenticated
 */

var isAuth = function(req, res, next){
  (req.isAuthenticated()) ? next() : res.send(403);
};

/*
 * Check if current user is project leader
 */

var isProjectLeader = function(req, res, next){
  Project.findOne({ _id: req.params.project_id }, function(err, project) {
    if (err || !project) return res.send(404);
    if (!req.user.is_admin && req.user.id != project.leader) return res.send(401);
    req.project = project;
    next();
  });
};

/*
 * Load all projects
 */

var loadProjects = function(req, res, next) {
  Project.find({})
  .populate('contributors')
  .populate('followers')
  .populate('leader')
  .exec(function(err, projects) {
    if(err) return res.send(500);
    res.locals.projects = projects;
    res.locals.user = req.user;
    res.locals.userExists = userExistsInArray;
    next();
  });
};

/*
 * Load specific project
 */

var loadProject = function(req, res, next) {
  Project.findById(req.params.project_id)
  .populate('contributors')
  .populate('followers')
  .populate('leader')
  .exec(function(err, project) {
    if(err || !project) return res.send(500);
    res.locals.project = project;
    res.locals.user = req.user;
    res.locals.userExists = userExistsInArray;
    next();
  });
};

var userExistsInArray = function(user, arr){
  return _.find(arr, function(u){
    return (u.id == user.id);
  });
};

/*
 * Load searched projects
 * TODO: use mongoose plugin for keywords
 */

var loadSearchProjects = function(req, res, next) {
  var regex = new RegExp(req.query.q, 'i');
  var query = {};

  if(!req.query.q.length) return res.redirect('/api/projects');

  if(req.query.type === "title") query['title'] = regex;
  else if(req.query.type === "tag") query['tags'] = regex;
  else return res.send(500);

  Project
  .find(query, function(err, projects) {
    if(err) return res.send(500);
    res.locals.projects = projects;
    res.locals.user = req.user;
    res.locals.userExists = userExistsInArray;
    next();
  });
};

/*
 * If a github repo is provided, fetch the data
 */

var isGithubRepo = function(req, res, next) {
  if(req.body.repo_user && req.body.repo_name) {
    request.get('https://api.github.com/repos/' + req.body.repo_user + '/' + req.body.repo_name)
    .end(function(resp){
      if(resp.error) return res.send(500);
  
      req.body.title = resp.body.name;
      req.body.description = resp.body.description;
      req.body.link = resp.body.html_url;
      req.body.status = 'building';
      req.body.tags = resp.body.language;
      next();
    });  
  } else {
    next();
  }
}; 

/*
 * Check project fields
 */

var validateProject = function(req, res, next) {console.log(req.body);
  if(req.body.title && req.body.description) next();
  else res.send(500, "Project Title and Description fields must be complete.");
};

/*
 * Save new project
 */

var saveProject = function(req, res, next) {
{'fraction_non_alphanumeric': 0.17067425655118265, 'fraction_numerical': 0.005790558445382275, 'mean_word_length': 3.8362600854295206, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7168775', 'n_tokens_mistral': 3490, 'n_tokens_neox': 3393, 'n_words': 722}