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

module.exports = function requireMany(paths) {
  var modules = {}
    , paths = Array.isArray(paths) ? paths : [paths]
    , files = []
    , index = 0
    , options = {}
    , callback
    , done
    , args = Array.prototype.slice.call(arguments, 0);

  args.forEach(function (arg) {
    if ('object' === typeof arg) {
      return options = arg;
    }
    if ('function' === typeof arg && 'undefined' === typeof callback) {
      return callback = arg;
    }
    if ('function' === typeof arg && 'undefined' === typeof done) {
      return done = arg;
    }
  });

  if ('function' !== typeof callback) {
    callback = function callback(module, filePath, cb) {
      cb();
    };
  }

  if ('function' !== typeof done) {
    done = function done(err) {
      if (err) throw err;
    };
  }

  if (options.asArray) {
    modules = [];
  }

  function parsePath(_path) {
    if (path.existsSync(_path)) {
      if (fs.statSync(_path).isDirectory()) {
        fs.readdirSync(_path).forEach(function (file) {
          var curPath = path.join(_path, file);
          if (fs.statSync(curPath).isDirectory()) {
            options.recurse && parsePath(curPath);
          } else if (!options.predicate || ('function' === typeof options.predicate && options.predicate(curPath))) {
            files.push(curPath);
          }
        });
      } else {
        files.push(_path);
      }
    }
  };

  function processFile() {
    var filePath = files[index]
      , name = path.basename(filePath, path.extname(filePath))
      , dirname = path.dirname(filePath)
      , module;

    if (options.lazyLoad) {
      module = function() {
        return require(filePath);
      };
    } else {
      module = require(filePath);
    }

    if (options.asArray) {
      modules.push(module);
    } else {
      if ('function' === typeof module && module.name && module.name.length > 0) {
        name = module.name;
      }
      modules[name] = module;
    }

    callback(module, filePath, function(err) {
      if (err) {
        done(err);
      } else {
        index += 1;
        if (index == files.length) {
          done(null);
        } else {
          processFile();
        }
      }
    });
  };

  paths.forEach(parsePath);

  if (files.length > 0) {
    processFile();
  } else {
    done();
  }

  return modules;
}<commit_msg>Ensure directory contents are sorted<commit_after>var path = require('path')
  , fs = require('fs');

module.exports = function requireMany(paths) {
  var modules = {}
    , paths = Array.isArray(paths) ? paths : [paths]
    , files = []
    , index = 0
    , options = {}
    , callback
    , done
    , args = Array.prototype.slice.call(arguments, 0);

  args.forEach(function (arg) {
    if ('object' === typeof arg) {
      return options = arg;
    }
    if ('function' === typeof arg && 'undefined' === typeof callback) {
      return callback = arg;
    }
    if ('function' === typeof arg && 'undefined' === typeof done) {
      return done = arg;
    }
  });

  if ('function' !== typeof callback) {
    callback = function callback(module, filePath, cb) {
      cb();
    };
  }

  if ('function' !== typeof done) {
    done = function done(err) {
      if (err) throw err;
    };
  }

  if (options.asArray) {
    modules = [];
  }

  function parsePath(_path) {
    if (path.existsSync(_path)) {
      if (fs.statSync(_path).isDirectory()) {
        fs.readdirSync(_path).sort().forEach(function (file) {
          var curPath = path.join(_path, file);
          if (fs.statSync(curPath).isDirectory()) {
            options.recurse && parsePath(curPath);
          } else if (!options.predicate || ('function' === typeof options.predicate && options.predicate(curPath))) {
            files.push(curPath);
          }
        });
      } else {
        files.push(_path);
      }
    }
  };

  function processFile() {
    var filePath = files[index]
      , name = path.basename(filePath, path.extname(filePath))
      , dirname = path.dirname(filePath)
      , module;

    if (options.lazyLoad) {
      module = function() {
        return require(filePath);
      };
    } else {
      module = require(filePath);
    }

    if (options.asArray) {
      modules.push(module);
    } else {
      if ('function' === typeof module && module.name && module.name.length > 0) {
        name = module.name;
      }
      modules[name] = module;
    }

    callback(module, filePath, function(err) {
      if (err) {
        done(err);
      } else {
        index += 1;
        if (index == files.length) {
          done(null);
        } else {
          processFile();
        }
      }
    });
  };

  paths.forEach(parsePath);

  if (files.length > 0) {
    processFile();
  } else {
    done();
  }

  return modules;
}<|endoftext|>


<commit_before>'use strict';
var debug = require('debug')('revvedfinder');
var path = require('path');
var _ = require('lodash');

// Allow to find, on disk, the revved version of a furnished file
//
// +locator+ : this is either:
//    - a hash mapping files with their revved versions
//    - a function that will return a list of file matching a given pattern (for example grunt.file.expand)
//
var RevvedFinder = module.exports = function (locator) {
  if (_.isFunction(locator)) {
    debug('using function locator');
    this.expandfn = locator;
  } else {
    debug('using file locator %s', locator);
    this.mapping = locator;
  }
};

var regexpQuote = function (str) {
  return (str + '').replace(/([.?*+\^$\[\]\\(){}|\-])/g, '\\$1');
};

RevvedFinder.prototype.getCandidatesFromMapping = function(file, searchPaths) {
  var dirname = path.dirname(file);
  var candidates = [];
  var self = this;

  searchPaths.forEach(function(sp) {
    var key = path.normalize(path.join(sp, file)).replace(/\\/g, '/');
    debug('Looking at mapping for %s (from %s/%s)',key, sp, file);

    if (self.mapping[key]) {
      // We need to transform the actual file to a form that matches the one we received
      // For example if we received file 'foo/images/test.png' with searchPaths == ['dist'],
      // and found in mapping that 'dist/foo/images/test.png' has been renamed
      // 'dist/foo/images/test.1234.png' by grunt-rev, then we need to return
      // 'foo/images/test.1234.png'
      var cfile = path.basename(self.mapping[key]);
      candidates.push(dirname + '/' + cfile);
      debug('Found a candidate: %s/%s',dirname, cfile);
    }
  });

  return candidates;
}
;
RevvedFinder.prototype.getCandidatesFromFS = function(file, searchPaths) {
  var extname = path.extname(file);
  var basename = path.basename(file, extname);
  var dirname = path.dirname(file);
  var hex = '[0-9a-fA-F]+';
  var regPrefix = '(' + hex + '\\.' + regexpQuote(basename) + ')';
  var regSuffix = '('+ regexpQuote(basename) + '\\.' + hex + regexpQuote(extname) + ')';
  var revvedRx = new RegExp(regPrefix + '|' + regSuffix);
  var candidates = [];
  var self = this;

  searchPaths.forEach(function(sp) {
    var searchString = path.join(sp, dirname, basename + '.*' + extname);
    var prefixSearchString = path.join(sp, dirname, '*.' + basename + extname);

    if (searchString.indexOf('#') === 0) {
      // patterns starting with # are treated as comments by the glob implementation which returns undefined,
      // which would cause an unhandled exception in self.expandfn below so the file is never written
      return;
    }

    debug('Looking for %s and %s on disk', searchString, prefixSearchString);

    var files = self.expandfn([searchString, prefixSearchString]);

    debug('Found ', files);

    // Keep only files that look like a revved file
    var goodFiles = files.filter(function(f) { return f.match(revvedRx); });

    // We must now remove the search path from the beginning, and add them to the
    // list of candidates
    goodFiles.forEach(function(gf) {
      var goodFileName = path.basename(gf);
      if (!file.match(/\//)) {
        // We only get a file (i.e. no dirs), so let's send back
        // what we found
        debug('Adding %s to candidates', goodFileName);
        candidates.push(goodFileName);
      } else {
        debug('Adding %s / %s to candidates', dirname, goodFileName);
        candidates.push(dirname + '/' + goodFileName);
      }
    });
  });

  return(candidates);
};

// Finds out candidates for file in the furnished searchPaths.
// It should return an array of candidates that are in the same format as the
// furnished file.
// For example, when given file 'images/test.png', and searchPaths of ['dist']
// the returned array should be something like ['images/test.1234.png']
//
RevvedFinder.prototype.getRevvedCandidates = function(file, searchPaths) {
  var candidates;

  // Our strategy depends on what we get at creation time: either a mapping, and we "just"
  // need to do look-up in the mapping, or an expand function and we need to find relevant files
  // on the disk
  // FIXME:

  if (this.mapping) {
    debug('Looking at mapping');
    candidates = this.getCandidatesFromMapping(file, searchPaths);
  }  else {
    debug('Looking on disk');
    candidates = this.getCandidatesFromFS(file, searchPaths);
  }

  return candidates;
};

//
// Find a revved version of +ofile+ (i.e. a file which name is ending with +ofile+), relatively
// to the furnished +searchDirs+.
// Let's imagine you have the following directory structure:
//  + build
//  |  |
//  |  +- css
//  |      |
//  |      + style.css
//  + images
//     |
//     + pic.2123.png
//
// and that somehow style.css is referencing '../../images/pic.png'
// When called like that:
//   revvedFinder.find('../../images/pic.png', 'build/css');
// the function must return
// '../../images/pic.2123.png'
//
// Note that +ofile+ should be a relative path to the looked for file
// (i.e. if it's an absolue path -- starting with / -- or an external one -- containing :// -- then
//  the original file is returned)
//
// It returns an object with 2 attributes:
//  name: which is the filename
//  base: which is the directory from searchDirs where we found the file
//
RevvedFinder.prototype.find = function find(ofile, searchDirs) {
    var file = ofile;
    var searchPaths = searchDirs;
    var absolute;
    var prefix;

    if (_.isString(searchDirs)) {
      searchPaths = [searchDirs];
    }

    debug('Looking for revved version of %s in ', ofile, searchPaths);

    //do not touch external files or the root
    // FIXME: Should get only relative files
    if (ofile.match(/:\/\//) || ofile === '') {
      return ofile;
    }

    if (file[0] === '/') {
      // We need to remember this is an absolute file, but transform it
      // to a relative one
      absolute = true;
      file = file.replace(/^(\/+)/, function(match, header) { prefix = header; return '';});
    }

    var filepaths = this.getRevvedCandidates(file, searchPaths);

    var filepath = filepaths[0];
    debug('filepath is now ', filepath);

    // not a file in temp, skip it
    if (!filepath) {
      return ofile;
    }

    // var filename = path.basename(filepath);
    // handle the relative prefix (with always unix like path even on win32)
    // if (dirname !== '.') {
    //   filename = [dirname, filename].join('/');
    // }

    if (absolute) {
      filepath = prefix + filepath;
    }

    debug('Let\'s return %s', filepath);
    return filepath;
  };
<commit_msg>Revert "Fixes getCandidatesFromMapping on windows"<commit_after>'use strict';
var debug = require('debug')('revvedfinder');
var path = require('path');
var _ = require('lodash');

// Allow to find, on disk, the revved version of a furnished file
//
// +locator+ : this is either:
//    - a hash mapping files with their revved versions
//    - a function that will return a list of file matching a given pattern (for example grunt.file.expand)
//
var RevvedFinder = module.exports = function (locator) {
  if (_.isFunction(locator)) {
    debug('using function locator');
    this.expandfn = locator;
  } else {
    debug('using file locator %s', locator);
    this.mapping = locator;
  }
};

var regexpQuote = function (str) {
  return (str + '').replace(/([.?*+\^$\[\]\\(){}|\-])/g, '\\$1');
};

RevvedFinder.prototype.getCandidatesFromMapping = function(file, searchPaths) {
  var dirname = path.dirname(file);
  var candidates = [];
  var self = this;

  searchPaths.forEach(function(sp) {
    var key = path.normalize(path.join(sp, file));
    debug('Looking at mapping for %s (from %s/%s)',key, sp, file);

    if (self.mapping[key]) {
      // We need to transform the actual file to a form that matches the one we received
      // For example if we received file 'foo/images/test.png' with searchPaths == ['dist'],
      // and found in mapping that 'dist/foo/images/test.png' has been renamed
      // 'dist/foo/images/test.1234.png' by grunt-rev, then we need to return
      // 'foo/images/test.1234.png'
      var cfile = path.basename(self.mapping[key]);
      candidates.push(dirname + '/' + cfile);
      debug('Found a candidate: %s/%s',dirname, cfile);
    }
  });

  return candidates;
}
;
RevvedFinder.prototype.getCandidatesFromFS = function(file, searchPaths) {
  var extname = path.extname(file);
  var basename = path.basename(file, extname);
  var dirname = path.dirname(file);
  var hex = '[0-9a-fA-F]+';
  var regPrefix = '(' + hex + '\\.' + regexpQuote(basename) + ')';
  var regSuffix = '('+ regexpQuote(basename) + '\\.' + hex + regexpQuote(extname) + ')';
  var revvedRx = new RegExp(regPrefix + '|' + regSuffix);
  var candidates = [];
  var self = this;

  searchPaths.forEach(function(sp) {
    var searchString = path.join(sp, dirname, basename + '.*' + extname);
    var prefixSearchString = path.join(sp, dirname, '*.' + basename + extname);

    if (searchString.indexOf('#') === 0) {
      // patterns starting with # are treated as comments by the glob implementation which returns undefined,
      // which would cause an unhandled exception in self.expandfn below so the file is never written
      return;
    }

    debug('Looking for %s and %s on disk', searchString, prefixSearchString);

    var files = self.expandfn([searchString, prefixSearchString]);

    debug('Found ', files);

    // Keep only files that look like a revved file
    var goodFiles = files.filter(function(f) { return f.match(revvedRx); });

    // We must now remove the search path from the beginning, and add them to the
    // list of candidates
    goodFiles.forEach(function(gf) {
      var goodFileName = path.basename(gf);
      if (!file.match(/\//)) {
        // We only get a file (i.e. no dirs), so let's send back
        // what we found
        debug('Adding %s to candidates', goodFileName);
        candidates.push(goodFileName);
      } else {
        debug('Adding %s / %s to candidates', dirname, goodFileName);
        candidates.push(dirname + '/' + goodFileName);
      }
    });
  });

  return(candidates);
};

// Finds out candidates for file in the furnished searchPaths.
// It should return an array of candidates that are in the same format as the
// furnished file.
// For example, when given file 'images/test.png', and searchPaths of ['dist']
// the returned array should be something like ['images/test.1234.png']
//
RevvedFinder.prototype.getRevvedCandidates = function(file, searchPaths) {
  var candidates;

  // Our strategy depends on what we get at creation time: either a mapping, and we "just"
  // need to do look-up in the mapping, or an expand function and we need to find relevant files
  // on the disk
  // FIXME:

  if (this.mapping) {
    debug('Looking at mapping');
    candidates = this.getCandidatesFromMapping(file, searchPaths);
  }  else {
    debug('Looking on disk');
    candidates = this.getCandidatesFromFS(file, searchPaths);
  }

  return candidates;
};

//
// Find a revved version of +ofile+ (i.e. a file which name is ending with +ofile+), relatively
// to the furnished +searchDirs+.
// Let's imagine you have the following directory structure:
//  + build
//  |  |
//  |  +- css
//  |      |
//  |      + style.css
//  + images
//     |
//     + pic.2123.png
//
// and that somehow style.css is referencing '../../images/pic.png'
// When called like that:
//   revvedFinder.find('../../images/pic.png', 'build/css');
// the function must return
// '../../images/pic.2123.png'
//
// Note that +ofile+ should be a relative path to the looked for file
// (i.e. if it's an absolue path -- starting with / -- or an external one -- containing :// -- then
//  the original file is returned)
//
// It returns an object with 2 attributes:
//  name: which is the filename
//  base: which is the directory from searchDirs where we found the file
//
RevvedFinder.prototype.find = function find(ofile, searchDirs) {
    var file = ofile;
    var searchPaths = searchDirs;
    var absolute;
    var prefix;

    if (_.isString(searchDirs)) {
      searchPaths = [searchDirs];
    }

    debug('Looking for revved version of %s in ', ofile, searchPaths);

    //do not touch external files or the root
    // FIXME: Should get only relative files
    if (ofile.match(/:\/\//) || ofile === '') {
      return ofile;
    }

    if (file[0] === '/') {
      // We need to remember this is an absolute file, but transform it
      // to a relative one
      absolute = true;
      file = file.replace(/^(\/+)/, function(match, header) { prefix = header; return '';});
    }

    var filepaths = this.getRevvedCandidates(file, searchPaths);

    var filepath = filepaths[0];
    debug('filepath is now ', filepath);

    // not a file in temp, skip it
    if (!filepath) {
      return ofile;
    }

    // var filename = path.basename(filepath);
    // handle the relative prefix (with always unix like path even on win32)
    // if (dirname !== '.') {
    //   filename = [dirname, filename].join('/');
    // }

    if (absolute) {
      filepath = prefix + filepath;
    }

    debug('Let\'s return %s', filepath);
    return filepath;
  };
<|endoftext|>


<commit_before>const Router = require('express').Router;
const router = Router();
const Post = require('../models/post');

router
  .get('/', (req, res, next) => {
    Post.find({})
      .lean()
      .then(posts => res.send(posts))
      .catch(next);
  })

  .post('/', (req, res, next) => {
    Post.create(req.body)
      .then(post => res.send(post))
      .catch(next);
  })

  .post('/:id/likes', (req, res, next) => {
    const id = req.params.id;
    Post.findByIdAndUpdate(id, { $addToSet:  { likes: { $each: [req.body._id] } } }, { new: true })
      .then(post =>
        res.send({
          likes: post.likes.length
        }))
      .catch(next);
  })

  .post('/:id/comments', (req, res, next) => {
    const id = req.params.id;
    Post.findByIdAndUpdate(id, {
      $push: {
        comments: {
          user: req.user.id,
          text: req.body //is this right?
        }
      }
    })
      .then(post => res.send(post))
      .catch(next);
  });

module.exports = router;<commit_msg>updated likes route<commit_after>const Router = require('express').Router;
const router = Router();
const Post = require('../models/post');

router
  .get('/', (req, res, next) => {
    Post.find({})
      .lean()
      .then(posts => res.send(posts))
      .catch(next);
  })

  .post('/', (req, res, next) => {
    req.body.user = req.user.id;
    Post.create(req.body)
      .then(post => res.send(post))
      .catch(next);
  })

  .post('/:id/likes', (req, res, next) => {
    const id = req.params.id;
    Post.findByIdAndUpdate(id, { $addToSet:  { likes: { $each: [req.user.id] } } }, { new: true })
      .then(post => res.send({likes: post.likes}))
      .catch(next);
  })

  .post('/:id/comments', (req, res, next) => {
    const id = req.params.id;
    Post.findByIdAndUpdate(id, {
      $push: {
        comments: {
          user: req.user.id,
          text: req.body //is this right?
        }
      }
    })
      .then(post => res.send(post))
      .catch(next);
  });

module.exports = router;<|endoftext|>


<commit_before>var ddb = require('../../config/dynamo_database').ddb;
var passport = require('passport');
var uuid = require('node-uuid');
var email = require('../service/email_service');
var mail_config =require('../../config/mail_config');
var userModel = require('../model/userModel');
var bcrypt =require('bcrypt');
var Promise = require('promise');
var _ = require("underscore");
var mysql = require('../../config/mysql_database').connection;

multipleFindUsers = function(resolve, reject, options, result){
	return ddb.scan('accounts', options, function (err, users) {
		if (!err){
			if(result == undefined)
				result = [];

			users.items.forEach(function(element){
				var nome = element.nome || '';
				var username = element.username;
				if(username.indexOf("@") > -1)
					result.push(username + ';' + nome + ';');
			});

			if(users.lastEvaluatedKey.hash == undefined){
				return resolve(result);
			}else{
				options.exclusiveStartKey = {hash: users.lastEvaluatedKey.hash};
				multipleFindBlindRatings(resolve,reject,options, result);
			}
		}else {
			return reject(err);
		}
	});
};

exports.findAll = function (req, res){

	var promise = new Promise(function(resolve, reject){
		multipleFindUsers(resolve,reject, {});
	});

	promise.then(function(result) {
		return res.send(result);

	}, function(err){
		console.log(err);
		return res.send(400,err);
	});
};

exports.update = function (req, res){
	var user = userModel.updateUser(req, false);
	res.send(202);
	return ddb.updateItem('accounts', req._passport.session.user, null, user, function (err, users) {
		if (!err) {
			console.log("Updated user");
		} else {
			console.log(err);
		}
	});
};

exports.findById = function (req, res){
	if(!req._passport.session.user) return res.send(401);
	var opts = {
		attributesToGet: [
			'username',
			'escolaridade',
			'ratedProposals',
			'preferenciaPoliticaPublica',
			'sexo',
			'nome',
			'provider',
			'partidoPreferencia',
			'engajamentoPolitico',
			'renda',
			'cidade',
			'blindRatedProposals',
			'cidadeOndeVota',
			'updated_at',
			'dataNascimento',
			'created_at'
		]
	};
	return ddb.getItem('accounts', req._passport.session.user, null, opts, function (err, user) {
		if (!err) {
			return res.send(user);
		} else {
			return console.log(err);
		}
	});
};

exports.delete = function (req, res){
	ddb.deleteItem('accounts', req.params.username, null, {},  function (err, user) {
		if (!err) {
			console.log("Removed user");
			return res.send('');
		} else {
			console.log(err);
		}
	});
};

exports.register =  function(req, res, next) {
	var user = userModel.newUser(req, true);

	ddb.putItem('accounts', user, {}, function (err) {
		if (!err) {
			email.sendMail(mail_config.regularMailFrom, user.username, 'Confirmação de email', email.templateConfirm(user.comfirmationPass));
			return console.log("Created User");
		} else {
			return console.log(err);
		}
	});

	req.logIn(user, function(err) {
		if(err)
			return next(err);
		if(req.body.rememberme){
			req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 7;
		}
		res.json(200, { "user": user });
	});
}

exports.login = function(req, res, next) {
	passport.authenticate('local', function(err, user) {

		if(err)     { return next(err); }
		if(!user)   { return res.send(400); }

		req.logIn(user, function(err) {
			if(err) {
				return next(err);
			}
			if(req.body.rememberme){
				req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 7;
			}
			res.json(200, { "user": user });
		});
	})(req, res, next);
}

exports.logout = function(req, res) {
	req.logout();
	res.send(200);
}

exports.validadeMail = function (req, res){

	ddb.getItem('accounts', req.params.username, null, {}, function (err, user) {
		if (!err) {
			if(user.comfirmationPass == req.params.comfirmationPass){
				ddb.updateItem('accounts', req.params.username, null, {emailConfirmed:{value:"true"}}, function (err, users) {
					if (!err) {
						console.log("email validado");
					} else {
						console.log(err);
					}
					return res.send(202, "OK");
				});
			}
		}

		return res.send(403, "NOK");
	});
};

returnRatingsProposals = function(res, user){
	var filter;
	var ratedProposals = [];
	var rating = [];

	if(user.ratedProposals == undefined)
		return res.send({});

	var response = {};

	user.ratedProposals.forEach(function(rated, index){
		response[rated.substr(0,rated.length - 1)] = parseInt(rated.substr(rated.length - 1));
	});

	return res.send(response);
};

multipleFindRatings = function(resolve, reject, options, result){
	return ddb.scan('ratings', options, function (err, ratings) {
		if (!err){
			if(result == undefined)
				result = ratings.items;
			else
				result = _.union(result, ratings.items);
			if(ratings.lastEvaluatedKey.hash == undefined){
				return resolve(result);
			}else{
				options.exclusiveStartKey = {hash: ratings.lastEvaluatedKey.hash, range : ratings.lastEvaluatedKey.range};
				multipleFindRatings(resolve,reject,options, result);
			}
		}else {
			return reject(err);
		}
	});
};

exports.findRatingsById = function (req, res){
	return ddb.getItem('accounts', req._passport.session.user, null, {}, function (err, user) {
		if (!err) {
			if(user.ratingsImported == undefined){

				var promise = new Promise(function(resolve, reject){
					multipleFindRatings(resolve,reject, {filter : { username: { eq: req._passport.session.user }}});
				});

				promise.then(function(result) {
					var ratedProposals = [];
					result.forEach(function(element){
						ratedProposals.push(element.id + element.nota.toString());
					});

					user.ratedProposals = ratedProposals;
					user.ratingsImported = true;

					returnRatingsProposals(res,user);

					var updatedUser = {ratingsImported: {value: 0, action: 'PUT' },
										ratedProposals: {value: ratedProposals, action: 'PUT' }};

					ddb.updateItem('accounts', user.username, null, updatedUser, function (err, users) {
						if (!err) {
							console.log("Updated user");
						} else {
							console.log(err);
						}
					});

				}, function(err){
					console.log(err);
					return res.send(400,err);
				});
			}else
				returnRatingsProposals(res,user);

		} else {
			console.log(err);
			return res.send(err);
		}
	});
};

multipleFindBlindRatings = function(resolve, reject, options, result){
	return ddb.scan('blindRatings', options, function (err, ratings) {
		if (!err){
			if(result == undefined)
				result = ratings.items;
			else
				result = _.union(result, ratings.items);
			if(ratings.lastEvaluatedKey.hash == undefined){
				return resolve(result);
			}else{
				options.exclusiveStartKey = {hash: ratings.lastEvaluatedKey.hash, range : ratings.lastEvaluatedKey.range};
				multipleFindBlindRatings(resolve,reject,options, result);
			}
		}else {
			return reject(err);
		}
	});
};

returnProposals = function(res, user){
	var filter;
	var blindRatedProposals = [];
	var blindRating = [];

	if(user.blindRatedProposals == undefined)
		return res.send([]);

	user.blindRatedProposals.forEach(function(rated, index){
		blindRating.push(parseInt(rated.substr(rated.length - 1)));
		blindRatedProposals.push(rated.substr(0,rated.length - 1));
	});

	if(blindRatedProposals.length == 0)
		return res.send(200,[]);
	if(blindRatedProposals.length == 1)
		filter = {filter : { id: { eq : blindRatedProposals[0]}}}
	else
		filter = {filter : { id: { in : blindRatedProposals}}}

	ddb.scan('proposals', filter, function (err, proposals) {
		if (!err) {
			proposals.items.forEach(function(element){
				blindRatedProposals.forEach(function(rated, index){
					if(element.id == rated)
						element.nota = blindRating[index];
				});
			});
			return res.send(proposals.items);
		} else {
			console.log(err);
			return res.send(400,err);
		}
	});
};

exports.findCompleteBlindRatingsById = function (req, res){
	return ddb.getItem('accounts', req._passport.session.user, null, {}, function (err, user) {
		if (!err) {
			if(user.imported == undefined){

				var promise = new Promise(function(resolve, reject){
					multipleFindBlindRatings(resolve,reject, {filter : { username: { eq: req._passport.session.user }}});
				});

				promise.then(function(result) {
					var blindRatedProposals = [];
					result.forEach(function(element){
						blindRatedProposals.push(element.id + element.nota.toString());
					});

					user.blindRatedProposals = blindRatedProposals;
					user.imported = true;

					returnProposals(res,user);

					var updatedUser = {imported: {value: 0, action: 'PUT' },
										blindRatedProposals: {value: blindRatedProposals, action: 'PUT' }};

					ddb.updateItem('accounts', user.username, null, updatedUser, function (err, users) {
						if (!err) {
							console.log("Updated user");
						} else {
							console.log(err);
						}
					});

				}, function(err){
					console.log(err);
					return res.send(400,err);
				});
			}else
				returnProposals(res,user);

		} else {
			console.log(err);
			return res.send(err);
		}
	});
};

exports.profileHashUFC = function(req, res){

	return ddb.getItem('accounts', req._passport.session.user, null, {}, function (err, user) {
		if (!err) {
			var hash = user.id || user.provider_id;
			res.send({hash: hash});
			mysql.query('INSERT INTO userHashUFC (id, hash) VALUE (?, ?)',
			[user.username, hash],
			function(err, rows, fields) {
				if (err) console.log(err);
			});
		} else {
			return console.log(err);
		}
	});
};

exports.profileNameHashUFC = function(req, res){
	return mysql.query('SELECT id FROM userHashUFC WHERE hash = ?',
	[req.params.hash],
	function(err, rows, fields) {
		if (err) console.log(err);

		if(rows.length == 0 )
			res.send(400);
		else
			return ddb.getItem('accounts', rows[0].id, null, {}, function (err, user) {
				if (!err) {
					res.send({name: user.nome || ''});
				} else {
					return console.log(err);
				}
			});
	});
};<commit_msg>resolvendo problemas do aws<commit_after>var ddb = require('../../config/dynamo_database').ddb;
var passport = require('passport');
var uuid = require('node-uuid');
var email = require('../service/email_service');
var mail_config =require('../../config/mail_config');
var userModel = require('../model/userModel');
var bcrypt =require('bcrypt');
var Promise = require('promise');
var _ = require("underscore");
var mysql = require('../../config/mysql_database').connection;

multipleFindUsers = function(resolve, reject, options, result){
	return ddb.scan('accounts', options, function (err, users) {
		if (!err){
			if(result == undefined)
				result = [];

			users.items.forEach(function(element){
				var nome = element.nome || '';
				var username = element.username;
				if(username.indexOf("@") > -1)
					result.push(username + ';' + nome + ';');
			});

			if(users.lastEvaluatedKey.hash == undefined){
				return resolve(result);
			}else{
				options.exclusiveStartKey = {hash: users.lastEvaluatedKey.hash, range : null};
				multipleFindBlindRatings(resolve,reject,options, result);
			}
		}else {
			return reject(err);
		}
	});
};

exports.findAll = function (req, res){

	var promise = new Promise(function(resolve, reject){
		multipleFindUsers(resolve,reject, {});
	});

	promise.then(function(result) {
		return res.send(result);

	}, function(err){
		console.log(err);
		return res.send(400,err);
	});
};

exports.update = function (req, res){
	var user = userModel.updateUser(req, false);
	res.send(202);
	return ddb.updateItem('accounts', req._passport.session.user, null, user, function (err, users) {
		if (!err) {
			console.log("Updated user");
		} else {
			console.log(err);
		}
	});
};

exports.findById = function (req, res){
	if(!req._passport.session.user) return res.send(401);
	var opts = {
		attributesToGet: [
			'username',
			'escolaridade',
			'ratedProposals',
			'preferenciaPoliticaPublica',
			'sexo',
			'nome',
			'provider',
			'partidoPreferencia',
			'engajamentoPolitico',
			'renda',
			'cidade',
			'blindRatedProposals',
			'cidadeOndeVota',
			'updated_at',
			'dataNascimento',
			'created_at'
		]
	};
	return ddb.getItem('accounts', req._passport.session.user, null, opts, function (err, user) {
		if (!err) {
			return res.send(user);
		} else {
			return console.log(err);
		}
	});
};

exports.delete = function (req, res){
	ddb.deleteItem('accounts', req.params.username, null, {},  function (err, user) {
		if (!err) {
			console.log("Removed user");
			return res.send('');
		} else {
			console.log(err);
		}
	});
};

exports.register =  function(req, res, next) {
	var user = userModel.newUser(req, true);

	ddb.putItem('accounts', user, {}, function (err) {
		if (!err) {
			email.sendMail(mail_config.regularMailFrom, user.username, 'Confirmação de email', email.templateConfirm(user.comfirmationPass));
			return console.log("Created User");
		} else {
			return console.log(err);
		}
	});

	req.logIn(user, function(err) {
		if(err)
			return next(err);
		if(req.body.rememberme){
			req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 7;
		}
		res.json(200, { "user": user });
	});
}

exports.login = function(req, res, next) {
	passport.authenticate('local', function(err, user) {

		if(err)     { return next(err); }
		if(!user)   { return res.send(400); }

		req.logIn(user, function(err) {
			if(err) {
				return next(err);
			}
			if(req.body.rememberme){
				req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 7;
			}
			res.json(200, { "user": user });
		});
	})(req, res, next);
}

exports.logout = function(req, res) {
	req.logout();
	res.send(200);
}

exports.validadeMail = function (req, res){

	ddb.getItem('accounts', req.params.username, null, {}, function (err, user) {
		if (!err) {
			if(user.comfirmationPass == req.params.comfirmationPass){
				ddb.updateItem('accounts', req.params.username, null, {emailConfirmed:{value:"true"}}, function (err, users) {
					if (!err) {
						console.log("email validado");
					} else {
						console.log(err);
					}
					return res.send(202, "OK");
				});
			}
		}

		return res.send(403, "NOK");
	});
};

returnRatingsProposals = function(res, user){
	var filter;
	var ratedProposals = [];
	var rating = [];

	if(user.ratedProposals == undefined)
		return res.send({});

	var response = {};

	user.ratedProposals.forEach(function(rated, index){
		response[rated.substr(0,rated.length - 1)] = parseInt(rated.substr(rated.length - 1));
	});

	return res.send(response);
};

multipleFindRatings = function(resolve, reject, options, result){
	return ddb.scan('ratings', options, function (err, ratings) {
		if (!err){
			if(result == undefined)
				result = ratings.items;
			else
				result = _.union(result, ratings.items);
			if(ratings.lastEvaluatedKey.hash == undefined){
				return resolve(result);
			}else{
				options.exclusiveStartKey = {hash: ratings.lastEvaluatedKey.hash, range : ratings.lastEvaluatedKey.range};
				multipleFindRatings(resolve,reject,options, result);
			}
		}else {
			return reject(err);
		}
	});
};

exports.findRatingsById = function (req, res){
	return ddb.getItem('accounts', req._passport.session.user, null, {}, function (err, user) {
		if (!err) {
			if(user.ratingsImported == undefined){

				var promise = new Promise(function(resolve, reject){
					multipleFindRatings(resolve,reject, {filter : { username: { eq: req._passport.session.user }}});
				});

				promise.then(function(result) {
					var ratedProposals = [];
					result.forEach(function(element){
						ratedProposals.push(element.id + element.nota.toString());
					});

					user.ratedProposals = ratedProposals;
					user.ratingsImported = true;

					returnRatingsProposals(res,user);

					var updatedUser = {ratingsImported: {value: 0, action: 'PUT' },
										ratedProposals: {value: ratedProposals, action: 'PUT' }};

					ddb.updateItem('accounts', user.username, null, updatedUser, function (err, users) {
						if (!err) {
							console.log("Updated user");
						} else {
							console.log(err);
						}
					});

				}, function(err){
					console.log(err);
					return res.send(400,err);
				});
			}else
				returnRatingsProposals(res,user);

		} else {
			console.log(err);
			return res.send(err);
		}
	});
};

multipleFindBlindRatings = function(resolve, reject, options, result){
	return ddb.scan('blindRatings', options, function (err, ratings) {
		if (!err){
			if(result == undefined)
				result = ratings.items;
			else
				result = _.union(result, ratings.items);
			if(ratings.lastEvaluatedKey.hash == undefined){
				return resolve(result);
			}else{
				options.exclusiveStartKey = {hash: ratings.lastEvaluatedKey.hash, range : ratings.lastEvaluatedKey.range};
				multipleFindBlindRatings(resolve,reject,options, result);
			}
		}else {
			return reject(err);
		}
	});
};

returnProposals = function(res, user){
	var filter;
	var blindRatedProposals = [];
	var blindRating = [];

	if(user.blindRatedProposals == undefined)
		return res.send([]);

	user.blindRatedProposals.forEach(function(rated, index){
		blindRating.push(parseInt(rated.substr(rated.length - 1)));
		blindRatedProposals.push(rated.substr(0,rated.length - 1));
	});

	if(blindRatedProposals.length == 0)
		return res.send(200,[]);
	if(blindRatedProposals.length == 1)
		filter = {filter : { id: { eq : blindRatedProposals[0]}}}
	else
		filter = {filter : { id: { in : blindRatedProposals}}}

	ddb.scan('proposals', filter, function (err, proposals) {
		if (!err) {
			proposals.items.forEach(function(element){
				blindRatedProposals.forEach(function(rated, index){
					if(element.id == rated)
						element.nota = blindRating[index];
				});
			});
			return res.send(proposals.items);
		} else {
			console.log(err);
			return res.send(400,err);
		}
	});
};

exports.findCompleteBlindRatingsById = function (req, res){
	return ddb.getItem('accounts', req._passport.session.user, null, {}, function (err, user) {
		if (!err) {
			if(user.imported == undefined){

				var promise = new Promise(function(resolve, reject){
					multipleFindBlindRatings(resolve,reject, {filter : { username: { eq: req._passport.session.user }}});
				});

				promise.then(function(result) {
					var blindRatedProposals = [];
					result.forEach(function(element){
						blindRatedProposals.push(element.id + element.nota.toString());
					});

					user.blindRatedProposals = blindRatedProposals;
					user.imported = true;

					returnProposals(res,user);

					var updatedUser = {imported: {value: 0, action: 'PUT' },
										blindRatedProposals: {value: blindRatedProposals, action: 'PUT' }};

					ddb.updateItem('accounts', user.username, null, updatedUser, function (err, users) {
						if (!err) {
							console.log("Updated user");
						} else {
							console.log(err);
						}
					});

				}, function(err){
					console.log(err);
					return res.send(400,err);
				});
			}else
				returnProposals(res,user);

		} else {
			console.log(err);
			return res.send(err);
		}
	});
};

exports.profileHashUFC = function(req, res){

	return ddb.getItem('accounts', req._passport.session.user, null, {}, function (err, user) {
		if (!err) {
			var hash = user.id || user.provider_id;
			res.send({hash: hash});
			mysql.query('INSERT INTO userHashUFC (id, hash) VALUE (?, ?)',
			[user.username, hash],
			function(err, rows, fields) {
				if (err) console.log(err);
			});
		} else {
			return console.log(err);
		}
	});
};

exports.profileNameHashUFC = function(req, res){
	return mysql.query('SELECT id FROM userHashUFC WHERE hash = ?',
	[req.params.hash],
	function(err, rows, fields) {
		if (err) console.log(err);

		if(rows.length == 0 )
			res.send(400);
		else
			return ddb.getItem('accounts', rows[0].id, null, {}, function (err, user) {
				if (!err) {
					res.send({name: user.nome || ''});
				} else {
					return console.log(err);
				}
			});
	});
};<|endoftext|>


<commit_before>import { config } from "./config";
import { EventTarget } from "./events";

function objectOrFunction(x) {
  return isFunction(x) || (typeof x === "object" && x !== null);
}

function isFunction(x){
  return typeof x === "function";
}

var Promise = function(resolver) {
  var promise = this,
  resolved = false;

  if (typeof resolver !== 'function') {
    throw new TypeError('You must pass a resolver function as the sole argument to the promise constructor');
  }

  if (!(promise instanceof Promise)) {
    return new Promise(resolver);
  }

  var resolvePromise = function(value) {
    if (resolved) { return; }
    resolved = true;
    resolve(promise, value);
  };

  var rejectPromise = function(value) {
    if (resolved) { return; }
    resolved = true;
    reject(promise, value);
  };

  this.on('promise:failed', function(event) {
    this.trigger('error', { detail: event.detail });
  }, this);

  this.on('error', onerror);

  try {
    resolver(resolvePromise, rejectPromise);
  } catch(e) {
    rejectPromise(e);
  }
};

function onerror(event) {
  config.trigger('error', event);
}

var invokeCallback = function(type, promise, callback, event) {
  var hasCallback = isFunction(callback),
      value, error, succeeded, failed;

  if (hasCallback) {
    try {
      value = callback(event.detail);
      succeeded = true;
    } catch(e) {
      failed = true;
      error = e;
    }
  } else {
    value = event.detail;
    succeeded = true;
  }

  if (handleThenable(promise, value)) {
    return;
  } else if (hasCallback && succeeded) {
    resolve(promise, value);
  } else if (failed) {
    reject(promise, error);
  } else if (type === 'resolve') {
    resolve(promise, value);
  } else if (type === 'reject') {
    reject(promise, value);
  }
};

Promise.prototype = {
  constructor: Promise,

  isRejected: undefined,
  isFulfilled: undefined,
  rejectedReason: undefined,
  fulfillmentValue: undefined,

  then: function(done, fail) {
    this.off('error', onerror);

    var thenPromise = new this.constructor(function() {});

    if (this.isFulfilled) {
      config.async(function(promise) {
        invokeCallback('resolve', thenPromise, done, { detail: promise.fulfillmentValue });
      }, this);
    }

    if (this.isRejected) {
      config.async(function(promise) {
        invokeCallback('reject', thenPromise, fail, { detail: promise.rejectedReason });
      }, this);
    }

    this.on('promise:resolved', function(event) {
      invokeCallback('resolve', thenPromise, done, event);
    });

    this.on('promise:failed', function(event) {
      invokeCallback('reject', thenPromise, fail, event);
    });

    return thenPromise;
  },

  fail: function(fail) {
    return this.then(null, fail);
  }
};

EventTarget.mixin(Promise.prototype);

function resolve(promise, value) {
  if (promise === value) {
    fulfill(promise, value);
  } else if (!handleThenable(promise, value)) {
    fulfill(promise, value);
  }
}

function handleThenable(promise, value) {
  var then = null,
  resolved;

  try {
    if (promise === value) {
      throw new TypeError("A promises callback cannot return that same promise.");
    }

    if (objectOrFunction(value)) {
      then = value.then;

      if (isFunction(then)) {
        then.call(value, function(val) {
          if (resolved) { return true; }
          resolved = true;

          if (value !== val) {
            resolve(promise, val);
          } else {
            fulfill(promise, val);
          }
        }, function(val) {
          if (resolved) { return true; }
          resolved = true;

          reject(promise, val);
        });

        return true;
      }
    }
  } catch (error) {
    reject(promise, error);
    return true;
  }

  return false;
}

function fulfill(promise, value) {
  config.async(function() {
    promise.trigger('promise:resolved', { detail: value });
    promise.isFulfilled = true;
    promise.fulfillmentValue = value;
  });
}

function reject(promise, value) {
  config.async(function() {
    promise.trigger('promise:failed', { detail: value });
    promise.isRejected = true;
    promise.rejectedReason = value;
  });
}

export { Promise };
<commit_msg>alias catch and fail<commit_after>import { config } from "./config";
import { EventTarget } from "./events";

function objectOrFunction(x) {
  return isFunction(x) || (typeof x === "object" && x !== null);
}

function isFunction(x){
  return typeof x === "function";
}

var Promise = function(resolver) {
  var promise = this,
  resolved = false;

  if (typeof resolver !== 'function') {
    throw new TypeError('You must pass a resolver function as the sole argument to the promise constructor');
  }

  if (!(promise instanceof Promise)) {
    return new Promise(resolver);
  }

  var resolvePromise = function(value) {
    if (resolved) { return; }
    resolved = true;
    resolve(promise, value);
  };

  var rejectPromise = function(value) {
    if (resolved) { return; }
    resolved = true;
    reject(promise, value);
  };

  this.on('promise:failed', function(event) {
    this.trigger('error', { detail: event.detail });
  }, this);

  this.on('error', onerror);

  try {
    resolver(resolvePromise, rejectPromise);
  } catch(e) {
    rejectPromise(e);
  }
};

function onerror(event) {
  config.trigger('error', event);
}

var invokeCallback = function(type, promise, callback, event) {
  var hasCallback = isFunction(callback),
      value, error, succeeded, failed;

  if (hasCallback) {
    try {
      value = callback(event.detail);
      succeeded = true;
    } catch(e) {
      failed = true;
      error = e;
    }
  } else {
    value = event.detail;
    succeeded = true;
  }

  if (handleThenable(promise, value)) {
    return;
  } else if (hasCallback && succeeded) {
    resolve(promise, value);
  } else if (failed) {
    reject(promise, error);
  } else if (type === 'resolve') {
    resolve(promise, value);
  } else if (type === 'reject') {
    reject(promise, value);
  }
};

Promise.prototype = {
  constructor: Promise,

  isRejected: undefined,
  isFulfilled: undefined,
  rejectedReason: undefined,
  fulfillmentValue: undefined,

  then: function(done, fail) {
    this.off('error', onerror);

    var thenPromise = new this.constructor(function() {});

    if (this.isFulfilled) {
      config.async(function(promise) {
        invokeCallback('resolve', thenPromise, done, { detail: promise.fulfillmentValue });
      }, this);
    }

    if (this.isRejected) {
      config.async(function(promise) {
        invokeCallback('reject', thenPromise, fail, { detail: promise.rejectedReason });
      }, this);
    }

    this.on('promise:resolved', function(event) {
      invokeCallback('resolve', thenPromise, done, event);
    });

    this.on('promise:failed', function(event) {
      invokeCallback('reject', thenPromise, fail, event);
    });

    return thenPromise;
  },

  fail: function(onRejection) {
    return this.then(null, onRejection);
  }
};

Promise.prototype['catch'] = Promise.prototype.fail;

EventTarget.mixin(Promise.prototype);

function resolve(promise, value) {
  if (promise === value) {
    fulfill(promise, value);
  } else if (!handleThenable(promise, value)) {
    fulfill(promise, value);
  }
}

function handleThenable(promise, value) {
  var then = null,
  resolved;

  try {
    if (promise === value) {
      throw new TypeError("A promises callback cannot return that same promise.");
    }

    if (objectOrFunction(value)) {
      then = value.then;

      if (isFunction(then)) {
        then.call(value, function(val) {
          if (resolved) { return true; }
          resolved = true;

          if (value !== val) {
            resolve(promise, val);
          } else {
            fulfill(promise, val);
          }
        }, function(val) {
          if (resolved) { return true; }
          resolved = true;

          reject(promise, val);
        });

        return true;
      }
    }
  } catch (error) {
    reject(promise, error);
    return true;
  }

  return false;
}

function fulfill(promise, value) {
  config.async(function() {
    promise.trigger('promise:resolved', { detail: value });
    promise.isFulfilled = true;
    promise.fulfillmentValue = value;
  });
}

function reject(promise, value) {
  config.async(function() {
    promise.trigger('promise:failed', { detail: value });
    promise.isRejected = true;
    promise.rejectedReason = value;
  });
}

export { Promise };
<|endoftext|>


<commit_before>'use strict';

var angular = require('camunda-bpm-sdk-js/vendor/angular');

  var SearchFactory = [ '$location', '$rootScope', function($location, $rootScope) {

    var silent = false;

    $rootScope.$on('$routeUpdate', function(e, lastRoute) {
      if (silent) {
        silent = false;
      } else {
        $rootScope.$broadcast('$routeChanged', lastRoute);
      }
    });

    $rootScope.$on('$routeChangeSuccess', function(e, lastRoute) {
      silent = false;
    });

    var search = function() {
      var args = Array.prototype.slice(arguments);

      return $location.search.apply($location, arguments);
    }

    search.updateSilently = function(params) {
      var oldPath = $location.absUrl();

      angular.forEach(params, function(value, key) {
        $location.search(key, value);
      });

      var newPath = $location.absUrl();

      if (newPath != oldPath) {
        silent = true;
      }
    };

    return search;
  }];

  var searchModule = angular.module('camunda.common.search', []);

  searchModule.factory('search', SearchFactory);

  module.exports = searchModule;
<commit_msg>feat(search): allow changing URL without creating history entries<commit_after>'use strict';

var angular = require('camunda-bpm-sdk-js/vendor/angular');

  var SearchFactory = [ '$location', '$rootScope', function($location, $rootScope) {

    var silent = false;

    $rootScope.$on('$routeUpdate', function(e, lastRoute) {
      if (silent) {
        silent = false;
      } else {
        $rootScope.$broadcast('$routeChanged', lastRoute);
      }
    });

    $rootScope.$on('$routeChangeSuccess', function(e, lastRoute) {
      silent = false;
    });

    var search = function() {
      var args = Array.prototype.slice(arguments);

      return $location.search.apply($location, arguments);
    }

    search.updateSilently = function(params, replaceFlag) {
      var oldPath = $location.absUrl();

      angular.forEach(params, function(value, key) {
        $location.search(key, value);
      });

      var newPath = $location.absUrl();

      if (newPath != oldPath) {
        silent = true;
      }

      if(replaceFlag) {
        $location.replace();
      }
    };

    return search;
  }];

  var searchModule = angular.module('camunda.common.search', []);

  searchModule.factory('search', SearchFactory);

  module.exports = searchModule;
<|endoftext|>


<commit_before>var isArray = require("x-is-array")
var isString = require("x-is-string")

var VNode = require("../vtree/vnode.js")
var VText = require("../vtree/vtext.js")
var isVNode = require("../vtree/is-vnode")
var isVText = require("../vtree/is-vtext")
var isWidget = require("../vtree/is-widget")

var parseTag = require("./parse-tag")

module.exports = h

function h(tagName, properties, children) {
    var tag, props, childNodes

    if (!children) {
        if (isChildren(properties)) {
            children = properties
            properties = undefined
        }
    }

    tag = parseTag(tagName, properties)

    if (!isString(tag)) {
        props = tag.properties
        tag = tag.tagName
    } else {
        props = properties
    }

    if (isArray(children)) {
        var len = children.length

        for (var i = 0; i < len; i++) {
            var child = children[i]
            if (isString(child)) {
                children[i] = new VText(child)
            }
        }

        childNodes = children
    } else if (isString(children)) {
        childNodes = [new VText(children)]
    } else if (isChild(children)) {
        childNodes = [children]
    }

    return new VNode(tag, props, childNodes)
}

function isChild(x) {
    return isVNode(x) || isVText(x) || isWidget(x)
}

function isChildren(x) {
    return isArray(x) || isString(x) || isChild(x)
}
<commit_msg>add key to h<commit_after>var isArray = require("x-is-array")
var isString = require("x-is-string")

var VNode = require("../vtree/vnode.js")
var VText = require("../vtree/vtext.js")
var isVNode = require("../vtree/is-vnode")
var isVText = require("../vtree/is-vtext")
var isWidget = require("../vtree/is-widget")

var parseTag = require("./parse-tag")

module.exports = h

function h(tagName, properties, children) {
    var tag, props, childNodes, key

    if (!children) {
        if (isChildren(properties)) {
            children = properties
            properties = undefined
        }
    }

    tag = parseTag(tagName, properties)

    if (!isString(tag)) {
        props = tag.properties
        tag = tag.tagName
    } else {
        props = properties
    }

    if (isArray(children)) {
        var len = children.length

        for (var i = 0; i < len; i++) {
            var child = children[i]
            if (isString(child)) {
                children[i] = new VText(child)
            }
        }

        childNodes = children
    } else if (isString(children)) {
        childNodes = [new VText(children)]
    } else if (isChild(children)) {
        childNodes = [children]
    }

    if (props && "key" in props) {
        key = props.key
        delete props.key
    }

    return new VNode(tag, props, childNodes, key)
}

function isChild(x) {
    return isVNode(x) || isVText(x) || isWidget(x)
}

function isChildren(x) {
    return isArray(x) || isString(x) || isChild(x)
}
<|endoftext|>


<commit_before>var _ = require('lodash')
  , locale = require('locale');

module.exports = function (options) {
  if (!options) options = {};

  return function (req, res, next) {
    var model = req.getModel()
      , preffered = model.setNull('$locale.prefferedLocales', options.prefferedLocales)
      , supported = model.setNull('$locale.supportedLocales', options.supportedLocales);

    preffered = _(preffered).flatten().unique();
    preffered = new locale.Locales(preffered);
    model.set('$locale.locale', preffered.best(supported).toString());
    next();
  };
};<commit_msg>another refactor<commit_after>var _ = require('lodash')
  , locale = require('locale');

module.exports = function (options) {
  if (!options) options = {};

  return function (req, res, next) {
    var model = req.getModel()
      , preffered = model.setNull('$locale.preffered', options.preffered)
      , supported = model.setNull('$locale.supported', options.supported);

    preffered = _(preffered).flatten().unique();
    preffered = new locale.Locales(preffered);
    model.set('$locale.locale', preffered.best(supported).toString());
    next();
  };
};<|endoftext|>


<commit_before>"use strict";

const ModuleRegistry = require("./ModuleRegistry.js"),
	ID = require("./ID.js"),
	msg_types = require("webrtc-conductor").enums,
	pki = require("node-forge").pki,
	random = require("node-forge").random,
	cipher = require("node-forge").cipher,
	forgeUtil = require("node-forge").util,
	u = require("./UtilFunctions.js");

//handshake status codes.
const HSHAKE_UNKNOWN = 0,
	HSHAKE_SENT = 1,
	HSHAKE_OBTAINED = 2;

class ChordSignalChannel{
	constructor(chord){
		this.id =  "chord-signal";
		this.internalID = "Conductor-Chord";
		this.chord = chord;

		this.handshakes = {};

		chord.registerModule(this);
	}

	//Must implement:
	// 1) ConnectionVector
	// 2) ChordMessageHandler

	//
	// ConnectionVector
	//

	// Description of algorithm:
	// 1) Send a request to the ID you think you want - include your public key and id.
	// 2) On receipt, connectee sends back its true id and key.
	// 3) Use key to encrypt SDP - send offer.
	// Standard setup from here on out - trade encrypted SDP and ICE.

	onbind(){
	}

	send(id,type,data){
		u.log(this.chord, "Queueing command from conductor to send over chord:");
		u.log(this.chord, type);
		switch(type){
			//All of these calls RELY on an accurate key exchange beforehand.
			//These interactiona are queued.

			case msg_types.MSG_SDP_OFFER:
				this.queueOrPerformActionOn(id, id => {this.sendSDP(id, "offer", data)} );
				break;
			case msg_types.MSG_SDP_ANSWER:
				this.queueOrPerformActionOn(id, id => {this.sendSDP(id, "answer", data)} );
				break;
			case msg_types.MSG_ICE:
				this.queueOrPerformActionOn(id, id => {this.sendICE(id, data)} );
				break;
		}
	}

	onmessage(msg){
		let out = {
				type: null,
				data: null,
				id: null
			};

		u.log(this.chord, `Response requested at conductor via chord:`);

		switch(msg.handler){
			case "sdp-offer":
				u.log(this.chord, `SDP offer from ${out.id}`);

				out.type = msg_types.RESPONSE_SDP_OFFER;
				out.data = msg.data.sdp;
				break;
			case "sdp-answer":
				u.log(this.chord, `SDP answer from ${out.id}`);

				out.type = msg_types.RESPONSE_SDP_ANSWER;
				out.data = msg.data.sdp;
				break;
			case "ice":
				u.log(this.chord, `ICE candidate from ${out.id}`);

				out.type = msg_types.RESPONSE_ICE;
				out.data = msg.data.ice;
				break;
			default:
				u.log(this.chord, `Misc message from: ${out.id}`);

				out.type = msg_types.RESPONSE_NONE;
				break;
		}

		out.id = msg.src;

		return out;
	}

	close(){
	}

	//
	// ChordMessageHandler
	//

	delegate(message){
		u.log(this.chord, "Received message at chord signal channel:");
		u.log(this.chord, `${message}`);

		switch(message.handler){
			case "key-shake-init":
				this.recvHandshakeInit(message);
				break;
			case "key-shake-reply":
				this.recvHandshakeReply(message);
				break;
			case "sdp-offer":
			case "sdp-answer":
				this.recvSDP(message);
				break;
			case "ice":
				this.recvICE(message);
				break;
		}
	}

	//
	// Entry management
	//
	fetchOrCreateNodeEntry(id){
		if(!this.handshakes[id]){
			this.handshakes[id] = {
				id,
				queue: [],
				status: HSHAKE_UNKNOWN,
				pubKey: null
			};
		}

		return this.handshakes[id];
	}

	queueOrPerformActionOn(id, func){
		//If no handshake, or ongoing then queue action.
		//Otherwise, execute action with id of entry.
		let entry = this.fetchOrCreateNodeEntry(id);

		//noinspection FallThroughInSwitchStatementJS
		switch(entry.status){
			case HSHAKE_UNKNOWN:
				this.initiateHandshake(id);
				//falls through
			case HSHAKE_SENT:
				entry.queue.push(func);
				break;
			case HSHAKE_OBTAINED:
				this.clearActionQueue(entry);
				func(id);
				break;
		}
	}

	clearActionQueue(entry){
		u.log(this.chord, `Clearing action queue for ${entry.id}`);

		while(entry.queue.length)
			(entry.queue.shift())(entry.id);
	}

	finishEntry(lookupID, pubPEM, optNewName, optAesKey){
		let entry = this.fetchOrCreateNodeEntry(lookupID);

		entry.status = HSHAKE_OBTAINED;

		if(optNewName)
			this.renameEntry(lookupID, optNewName);

		entry.pubKey = pki.publicKeyFromPem(pubPEM);

		entry.aesKey = (optAesKey) ? optAesKey : random.getBytesSync(16);

		return entry;
	}

	renameEntry(oldName, newName){
		if(oldName===newName || !this.handshakes[oldName])
			return false;
		else {
			this.handshakes[newName] = this.handshakes[oldName];
			this.handshakes[newName].id = newName;
			delete this.handshakes[oldName];
		}
	}

	//
	// Handshake Functions
	//

	initiateHandshake(id){
		u.log(this.chord, `Initialising handshake with: ${id}`);

		let entry = this.fetchOrCreateNodeEntry(id);

		entry.status = HSHAKE_SENT;

		this.message("key-shake-init", ModuleRegistry.wrap({pub: this.chord.pubKeyPem}), id);
	}

	recvHandshakeInit(message){
		//Message has: pub.
		u.log(this.chord, `Received handshake from: ${message.src}`);

		let entry = this.finishEntry(message.src, message.data.pub);
		this.updateLastMessage(message);

		this.message("key-shake-reply", ModuleRegistry.wrap({
			origId: message.dest,
			pub: this.chord.pubKeyPem,
			encKey: entry.pubKey.encrypt(entry.aesKey, "RSA-OAEP")
		}), message.src);
	}

	recvHandshakeReply(message){
		//Message has: origId, pub, encKey.
		u.log(this.chord, `Received handshake reply from ${message.data.origId}: true ID ${message.src}.`);

		let entry = this.finishEntry(message.data.origId,
			message.data.pub,
			message.src,
			this.chord.key.privateKey.decrypt(message.data.encKey, "RSA-OAEP")
		);

		try {
			this.chord.conductor.renameConnection(message.data.origId, message.src);
		} finally {
			this.clearActionQueue(entry);
		}
	}

	//
	// RTC functions
	//

	sendSDP(id, type, msg){
		let entry = this.fetchOrCreateNodeEntry(id);

		let iv = random.getBytesSync(12),
			cipherObj = cipher.createCipher('AES-GCM', entry.aesKey);

		cipherObj.start({
			iv,
			additionalData: 'binary-encoded string',
			tagLength: 128
		});

		cipherObj.update(forgeUtil.createBuffer(JSON.stringify(msg)));
		cipherObj.finish();

		this.message("sdp-"+type, {
			sdpEnc: cipherObj.output.data,
			tag: cipherObj.mode.tag.data,
			iv: iv
		}, id);
	}

	sendICE(id, msg){
		let entry = this.fetchOrCreateNodeEntry(id);

		let iv = random.getBytesSync(12),
			cipherObj = cipher.createCipher('AES-GCM', entry.aesKey);

		cipherObj.start({
			iv,
			additionalData: 'binary-encoded string',
			tagLength: 128
		});

		cipherObj.update(forgeUtil.createBuffer(JSON.stringify(msg)));
		cipherObj.finish();

		this.message("ice", {
			iceEnc: cipherObj.output.data,
			tag: cipherObj.mode.tag.data,
			iv: iv
		}, id);
	}

	recvSDP(message){
		//Message has: sdpEnc, tag, iv

		this.updateLastMessage(message);

		let entry = this.fetchOrCreateNodeEntry(message.src),
			iv = message.data.iv,
			decipher = cipher.createDecipher('AES-GCM', entry.aesKey);

		decipher.start({
			iv,
			additionalData: 'binary-encoded string',
			tagLength: 128,
			tag: message.data.tag
		});

		decipher.update(forgeUtil.createBuffer(message.data.sdpEnc));
		let success = decipher.finish();

		message.data.sdp = (success) ? JSON.parse(decipher.output.data) : "";

		this.chord.conductor.response(message, this);
	}

	recvICE(message) {
		//Message has: iceEnc, tag, iv

		this.updateLastMessage(message);

		let entry = this.fetchOrCreateNodeEntry(message.src),
			iv = message.data.iv,
			decipher = cipher.createDecipher('AES-GCM', entry.aesKey);

		decipher.start({
			iv,
			additionalData: 'binary-encoded string',
			tagLength: 128,
			tag: message.data.tag
		});

		decipher.update(forgeUtil.createBuffer(message.data.iceEnc));
		let success = decipher.finish();

		message.data.ice = (success) ? JSON.parse(decipher.output.data) : "";

		this.chord.conductor.response(message, this);
	}

	//
	// Helpers
	//
	message(handler, data, dest) {
		let msg = this.chord.newMessage(this.id, handler, data, dest);

		if(this.handshakes[dest] && this.handshakes[dest].lastMessage)
			this.handshakes[dest].lastMessage.reply(msg);
		else
			this.chord.message(msg);
	}

	updateLastMessage(message){
		if(message.src && this.handshakes[message.src])
			this.handshakes[message.src].lastMessage = message;
	}

}

module.exports = ChordSignalChannel;<commit_msg>Should pass messages at signal if for another node.<commit_after>"use strict";

const ModuleRegistry = require("./ModuleRegistry.js"),
	ID = require("./ID.js"),
	msg_types = require("webrtc-conductor").enums,
	pki = require("node-forge").pki,
	random = require("node-forge").random,
	cipher = require("node-forge").cipher,
	forgeUtil = require("node-forge").util,
	u = require("./UtilFunctions.js");

//handshake status codes.
const HSHAKE_UNKNOWN = 0,
	HSHAKE_SENT = 1,
	HSHAKE_OBTAINED = 2;

class ChordSignalChannel{
	constructor(chord){
		this.id =  "chord-signal";
		this.internalID = "Conductor-Chord";
		this.chord = chord;

		this.handshakes = {};

		chord.registerModule(this);
	}

	//Must implement:
	// 1) ConnectionVector
	// 2) ChordMessageHandler

	//
	// ConnectionVector
	//

	// Description of algorithm:
	// 1) Send a request to the ID you think you want - include your public key and id.
	// 2) On receipt, connectee sends back its true id and key.
	// 3) Use key to encrypt SDP - send offer.
	// Standard setup from here on out - trade encrypted SDP and ICE.

	onbind(){
	}

	send(id,type,data){
		u.log(this.chord, "Queueing command from conductor to send over chord:");
		u.log(this.chord, type);
		switch(type){
			//All of these calls RELY on an accurate key exchange beforehand.
			//These interactiona are queued.

			case msg_types.MSG_SDP_OFFER:
				this.queueOrPerformActionOn(id, id => {this.sendSDP(id, "offer", data)} );
				break;
			case msg_types.MSG_SDP_ANSWER:
				this.queueOrPerformActionOn(id, id => {this.sendSDP(id, "answer", data)} );
				break;
			case msg_types.MSG_ICE:
				this.queueOrPerformActionOn(id, id => {this.sendICE(id, data)} );
				break;
		}
	}

	onmessage(msg){
		let out = {
				type: null,
				data: null,
				id: null
			};

		u.log(this.chord, `Response requested at conductor via chord:`);

		switch(msg.handler){
			case "sdp-offer":
				u.log(this.chord, `SDP offer from ${out.id}`);

				out.type = msg_types.RESPONSE_SDP_OFFER;
				out.data = msg.data.sdp;
				break;
			case "sdp-answer":
				u.log(this.chord, `SDP answer from ${out.id}`);

				out.type = msg_types.RESPONSE_SDP_ANSWER;
				out.data = msg.data.sdp;
				break;
			case "ice":
				u.log(this.chord, `ICE candidate from ${out.id}`);

				out.type = msg_types.RESPONSE_ICE;
				out.data = msg.data.ice;
				break;
			default:
				u.log(this.chord, `Misc message from: ${out.id}`);

				out.type = msg_types.RESPONSE_NONE;
				break;
		}

		out.id = msg.src;

		return out;
	}

	close(){
	}

	//
	// ChordMessageHandler
	//

	delegate(message){
		u.log(this.chord, "Received message at chord signal channel:");
		u.log(this.chord, `${message}`);

		//Band aid fix.
		//I can either do this or force proxying over the successor.
		//Ideally, we would just proxy when overwriting an existing successor...
		if(message.dest !== this.chord.id.idString && message.handler !== "key-shake-init")
			return message.pass();

		switch(message.handler){
			case "key-shake-init":
				this.recvHandshakeInit(message);
				break;
			case "key-shake-reply":
				this.recvHandshakeReply(message);
				break;
			case "sdp-offer":
			case "sdp-answer":
				this.recvSDP(message);
				break;
			case "ice":
				this.recvICE(message);
				break;
		}
	}

	//
	// Entry management
	//
	fetchOrCreateNodeEntry(id){
		if(!this.handshakes[id]){
			this.handshakes[id] = {
				id,
				queue: [],
				status: HSHAKE_UNKNOWN,
				pubKey: null
			};
		}

		return this.handshakes[id];
	}

	queueOrPerformActionOn(id, func){
		//If no handshake, or ongoing then queue action.
		//Otherwise, execute action with id of entry.
		let entry = this.fetchOrCreateNodeEntry(id);

		//noinspection FallThroughInSwitchStatementJS
		switch(entry.status){
			case HSHAKE_UNKNOWN:
				this.initiateHandshake(id);
				//falls through
			case HSHAKE_SENT:
				entry.queue.push(func);
				break;
			case HSHAKE_OBTAINED:
				this.clearActionQueue(entry);
				func(id);
				break;
		}
	}

	clearActionQueue(entry){
		u.log(this.chord, `Clearing action queue for ${entry.id}`);

		while(entry.queue.length)
			(entry.queue.shift())(entry.id);
	}

	finishEntry(lookupID, pubPEM, optNewName, optAesKey){
		let entry = this.fetchOrCreateNodeEntry(lookupID);

		entry.status = HSHAKE_OBTAINED;

		if(optNewName)
			this.renameEntry(lookupID, optNewName);

		entry.pubKey = pki.publicKeyFromPem(pubPEM);

		entry.aesKey = (optAesKey) ? optAesKey : random.getBytesSync(16);

		return entry;
	}

	renameEntry(oldName, newName){
		if(oldName===newName || !this.handshakes[oldName])
			return false;
		else {
			this.handshakes[newName] = this.handshakes[oldName];
			this.handshakes[newName].id = newName;
			delete this.handshakes[oldName];
		}
	}

	//
	// Handshake Functions
	//

	initiateHandshake(id){
		u.log(this.chord, `Initialising handshake with: ${id}`);

		let entry = this.fetchOrCreateNodeEntry(id);

		entry.status = HSHAKE_SENT;

		this.message("key-shake-init", ModuleRegistry.wrap({pub: this.chord.pubKeyPem}), id);
	}

	recvHandshakeInit(message){
		//Message has: pub.
		u.log(this.chord, `Received handshake from: ${message.src}`);

		let entry = this.finishEntry(message.src, message.data.pub);
		this.updateLastMessage(message);

		this.message("key-shake-reply", ModuleRegistry.wrap({
			origId: message.dest,
			pub: this.chord.pubKeyPem,
			encKey: entry.pubKey.encrypt(entry.aesKey, "RSA-OAEP")
		}), message.src);
	}

	recvHandshakeReply(message){
		//Message has: origId, pub, encKey.
		u.log(this.chord, `Received handshake reply from ${message.data.origId}: true ID ${message.src}.`);

		let entry = this.finishEntry(message.data.origId,
			message.data.pub,
			message.src,
			this.chord.key.privateKey.decrypt(message.data.encKey, "RSA-OAEP")
		);

		try {
			this.chord.conductor.renameConnection(message.data.origId, message.src);
		} finally {
			this.clearActionQueue(entry);
		}
	}

	//
	// RTC functions
	//

	sendSDP(id, type, msg){
		let entry = this.fetchOrCreateNodeEntry(id);

		let iv = random.getBytesSync(12),
			cipherObj = cipher.createCipher('AES-GCM', entry.aesKey);

		cipherObj.start({
			iv,
			additionalData: 'binary-encoded string',
			tagLength: 128
		});

		cipherObj.update(forgeUtil.createBuffer(JSON.stringify(msg)));
		cipherObj.finish();

		this.message("sdp-"+type, {
			sdpEnc: cipherObj.output.data,
			tag: cipherObj.mode.tag.data,
			iv: iv
		}, id);
	}

	sendICE(id, msg){
		let entry = this.fetchOrCreateNodeEntry(id);

		let iv = random.getBytesSync(12),
			cipherObj = cipher.createCipher('AES-GCM', entry.aesKey);

		cipherObj.start({
			iv,
			additionalData: 'binary-encoded string',
			tagLength: 128
		});

		cipherObj.update(forgeUtil.createBuffer(JSON.stringify(msg)));
		cipherObj.finish();

		this.message("ice", {
			iceEnc: cipherObj.output.data,
			tag: cipherObj.mode.tag.data,
			iv: iv
		}, id);
	}

	recvSDP(message){
		//Message has: sdpEnc, tag, iv

		this.updateLastMessage(message);

		let entry = this.fetchOrCreateNodeEntry(message.src),
			iv = message.data.iv,
			decipher = cipher.createDecipher('AES-GCM', entry.aesKey);

		decipher.start({
			iv,
			additionalData: 'binary-encoded string',
			tagLength: 128,
			tag: message.data.tag
		});

		decipher.update(forgeUtil.createBuffer(message.data.sdpEnc));
		let success = decipher.finish();

		message.data.sdp = (success) ? JSON.parse(decipher.output.data) : "";

		this.chord.conductor.response(message, this);
	}

	recvICE(message) {
		//Message has: iceEnc, tag, iv

		this.updateLastMessage(message);

		let entry = this.fetchOrCreateNodeEntry(message.src),
			iv = message.data.iv,
			decipher = cipher.createDecipher('AES-GCM', entry.aesKey);

		decipher.start({
			iv,
			additionalData: 'binary-encoded string',
			tagLength: 128,
			tag: message.data.tag
		});

		decipher.update(forgeUtil.createBuffer(message.data.iceEnc));
		let success = decipher.finish();

		message.data.ice = (success) ? JSON.parse(decipher.output.data) : "";

		this.chord.conductor.response(message, this);
	}

	//
	// Helpers
	//
	message(handler, data, dest) {
		let msg = this.chord.newMessage(this.id, handler, data, dest);

		if(this.handshakes[dest] && this.handshakes[dest].lastMessage)
			this.handshakes[dest].lastMessage.reply(msg);
		else
			this.chord.message(msg);
	}

	updateLastMessage(message){
		if(message.src && this.handshakes[message.src])
			this.handshakes[message.src].lastMessage = message;
	}

}

module.exports = ChordSignalChannel;<|endoftext|>


<commit_before>'use strict';
var Agent = require('./agent');
var EventEmitter = require('events').EventEmitter;
var fs = require('fs');
var path = require('path');
var persistenceName = '.mrpersistent';
var processor = require('./processor');
var request = require('./request');
var shared = require('../shared');
var utilities = require('./utilities');

/**
 * Runs the tasks in a queue and returns an event emitter.
 * @param {!Array.<!{address: string, options: !IOptions}>} tasks
 * @param {number=} maximum
 * @return {!IEmitter}
 */
module.exports = function(tasks, maximum) {
  var beginTimeInMs = Date.now();
  var emitter = new EventEmitter();
  var queue = new shared.common.Queue(maximum, function(task, done) {
    if (task.alias) return taskChapter(emitter, task, done);
    taskSeries(emitter, queue, task, done);
  }, function(err) {
    save(queue.save, function(saveErr) {
      if (err || saveErr) return emitter.emit('error', err || saveErr);
      emitter.emit('end', {timeInMs: Date.now() - beginTimeInMs});
    });
  });
  emitter.push = function(tasks) {
    queue.push(tasks);
  };
  process.nextTick(function() {
    queue.save = {};
    queue.push(tasks);
  });
  return emitter;
};

/**
 * Creates an agent.
 * @param {!Object} task
 * @param {function(Error, Agent)} done
 */
function createAgent(task, done) {
  processor(task.options, task.series, task.chapter, function(err, processors) {
    if (err) return done(err);
    var filePath = task.filePath;
    var Meta = shared.publisher.Meta;
    done(undefined, task.options.meta ?
      new Agent(filePath, processors) :
      new Agent(filePath, processors, new Meta(task.series, task.chapter)));
  });
}

/**
 * Enqueues the chapter.
 * @param {!IEmitter} emitter
 * @param {!Queue} queue
 * @param {!Object} task
 * @param {!IChapter} chapter
 * @param {function(Error)} done
 */
function enqueueChapter(emitter, queue, task, chapter, done) {
  if (utilities.excluded(task.options, chapter)) return process.nextTick(done);
  var alias = shared.common.alias(task.series, chapter, task.options.extension);
  if (!alias) return process.nextTick(done);
  var filePath = path.join(task.options.output || '', alias);
  if (enqueueChapterPersist(emitter, task, chapter, done)) return;
  utilities.duplicate(task.options, filePath, function(duplicate) {
    if (!duplicate) {
      queue.push({
        alias: alias,
        chapter: chapter,
        filePath: filePath,
        options: task.options,
        persistent: task.persistent,
        series: task.series
      });
    }
    done();
  });
}

/**
 * Checks and matches enqueuing chapter persistence records.
 * @param {!IEmitter} emitter
 * @param {!Object} task
 * @param {!IChapter} chapter
 * @param {function(Error)} done
 * @return {boolean}
 */
function enqueueChapterPersist(emitter, task, chapter, done) {
  var alias = shared.common.alias(task.series, chapter, task.options.extension);
  var identifier = String(chapter.identifier);
  if (typeof task.persistent[identifier] !== 'undefined') {
    var basename = path.basename(alias);
    if (basename === task.persistent[identifier]) {
      process.nextTick(done);
      return true;
    }
    var output = task.options.output || '';
    var title = shared.common.alias.invalidate(task.series.title);
    var previousPath = path.join(output, title, task.persistent[identifier]);
    var currentPath = path.join(task.options.output || '', alias);
    task.persistent[identifier] = basename;
    emitter.emit('data', {item: basename, type: 'switched'});
    fs.rename(previousPath, currentPath, done);
    return true;
  }
  return false;
}

/**
 * Enqueues the series.
 * @param {!IEmitter} emitter
 * @param {!Queue} queue
 * @param {!Object} task
 * @param {function(Error)} done
 */
function enqueueSeries(emitter, queue, task, done) {
  request(task.series, 'utf8', function(err) {
    if (err) return done(err);
    var title = shared.common.alias.invalidate(task.series.title);
    var filePath = path.join(task.options.output || '', title, persistenceName);
    fs.exists(filePath, function(exists) {
      if (!exists) {
        task.persistent = queue.save[filePath] = {};
        return enqueueSeriesNext(emitter, queue, task, done);
      }
      fs.readFile(filePath, 'utf8', function(err, contents) {
        if (err) return done(err);
        task.persistent = queue.save[filePath] = JSON.parse(contents);
        enqueueSeriesNext(emitter, queue, task, done);
      });
    });
  });
}

/**
 * Continues enqueuing the series.
 * @param {!IEmitter} emitter
 * @param {!Queue} queue
 * @param {!Object} task
 * @param {function(Error)} done
 */
function enqueueSeriesNext(emitter, queue, task, done) {
  shared.common.async.eachSeries(task.series.children, function(chapter, next) {
    if (!chapter) return next();
    enqueueChapter(emitter, queue, task, chapter, next);
  }, done);
}

/**
 * Saves each persistent record.
 * @param {!Object.<string, !Object>} records
 * @param {function(Error)} done
 */
function save(records, done) {
  shared.common.async.eachSeries(Object.keys(records), function(key, next) {
    fs.writeFile(key, JSON.stringify(records[key]), 'utf8', function() {
      // IGNORE: The error is ignored. While the error can be valid (due to
      // permissions, for example), it is considered likely to be the result of
      // attempting to write to a folder which has not been created by an agent.
      next();
    });
  }, done);
}

/**
 * Runs a chapter task.
 * @param {!EventEmitter} emitter
 * @param {!Object} task
 * @param {function(Error)} done
 */
function taskChapter(emitter, task, done) {
  var basename = path.basename(task.alias);
  var begin = Date.now();
  emitter.emit('data', {item: basename, type: 'fetching'});
  request(task.chapter, 'utf8', function(err) {
    if (err) return done(err);
    createAgent(task, function(err, agent) {
      if (err) return done(err);
      shared.publisher.mirror(agent, task.series, task.chapter, function(err) {
        if (err) return done(err);
        agent.publish(function(err) {
          if (err) return emitter.emit('error', err);
          if (!task.options.persistent) {
            task.persistent[task.chapter.identifier] = basename;
          }
          emitter.emit('data', {
            item: basename,
            timeInMs: Date.now() - begin,
            type: agent._disposed ? 'disposed' : 'finished'
          });
          done();
        });
      });
    });
  });
}

/**
 * Runs a series task.
 * @param {!EventEmitter} emitter
 * @param {!Queue} queue
 * @param {!Object} task
 * @param {function(Error)} done
 */
function taskSeries(emitter, queue, task, done) {
  task.series = shared.provider(task.address);
  if (task.series) return enqueueSeries(emitter, queue, task, done);
  emitter.emit('data', {item: task.address, type: 'obscured'});
  process.nextTick(done);
}
<commit_msg>Prettier persist file output.<commit_after>'use strict';
var Agent = require('./agent');
var EventEmitter = require('events').EventEmitter;
var fs = require('fs');
var path = require('path');
var persistenceName = '.mrpersistent';
var processor = require('./processor');
var request = require('./request');
var shared = require('../shared');
var utilities = require('./utilities');

/**
 * Runs the tasks in a queue and returns an event emitter.
 * @param {!Array.<!{address: string, options: !IOptions}>} tasks
 * @param {number=} maximum
 * @return {!IEmitter}
 */
module.exports = function(tasks, maximum) {
  var beginTimeInMs = Date.now();
  var emitter = new EventEmitter();
  var queue = new shared.common.Queue(maximum, function(task, done) {
    if (task.alias) return taskChapter(emitter, task, done);
    taskSeries(emitter, queue, task, done);
  }, function(err) {
    save(queue.save, function(saveErr) {
      if (err || saveErr) return emitter.emit('error', err || saveErr);
      emitter.emit('end', {timeInMs: Date.now() - beginTimeInMs});
    });
  });
  emitter.push = function(tasks) {
    queue.push(tasks);
  };
  process.nextTick(function() {
    queue.save = {};
    queue.push(tasks);
  });
  return emitter;
};

/**
 * Creates an agent.
 * @param {!Object} task
 * @param {function(Error, Agent)} done
 */
function createAgent(task, done) {
  processor(task.options, task.series, task.chapter, function(err, processors) {
    if (err) return done(err);
    var filePath = task.filePath;
    var Meta = shared.publisher.Meta;
    done(undefined, task.options.meta ?
      new Agent(filePath, processors) :
      new Agent(filePath, processors, new Meta(task.series, task.chapter)));
  });
}

/**
 * Enqueues the chapter.
 * @param {!IEmitter} emitter
 * @param {!Queue} queue
 * @param {!Object} task
 * @param {!IChapter} chapter
 * @param {function(Error)} done
 */
function enqueueChapter(emitter, queue, task, chapter, done) {
  if (utilities.excluded(task.options, chapter)) return process.nextTick(done);
  var alias = shared.common.alias(task.series, chapter, task.options.extension);
  if (!alias) return process.nextTick(done);
  var filePath = path.join(task.options.output || '', alias);
  if (enqueueChapterPersist(emitter, task, chapter, done)) return;
  utilities.duplicate(task.options, filePath, function(duplicate) {
    if (!duplicate) {
      queue.push({
        alias: alias,
        chapter: chapter,
        filePath: filePath,
        options: task.options,
        persistent: task.persistent,
        series: task.series
      });
    }
    done();
  });
}

/**
 * Checks and matches enqueuing chapter persistence records.
 * @param {!IEmitter} emitter
 * @param {!Object} task
 * @param {!IChapter} chapter
 * @param {function(Error)} done
 * @return {boolean}
 */
function enqueueChapterPersist(emitter, task, chapter, done) {
  var alias = shared.common.alias(task.series, chapter, task.options.extension);
  var identifier = String(chapter.identifier);
  if (typeof task.persistent[identifier] !== 'undefined') {
    var basename = path.basename(alias);
    if (basename === task.persistent[identifier]) {
      process.nextTick(done);
      return true;
    }
    var output = task.options.output || '';
    var title = shared.common.alias.invalidate(task.series.title);
    var previousPath = path.join(output, title, task.persistent[identifier]);
    var currentPath = path.join(task.options.output || '', alias);
    task.persistent[identifier] = basename;
    emitter.emit('data', {item: basename, type: 'switched'});
    fs.rename(previousPath, currentPath, done);
    return true;
  }
  return false;
}

/**
 * Enqueues the series.
 * @param {!IEmitter} emitter
 * @param {!Queue} queue
 * @param {!Object} task
 * @param {function(Error)} done
 */
function enqueueSeries(emitter, queue, task, done) {
  request(task.series, 'utf8', function(err) {
    if (err) return done(err);
    var title = shared.common.alias.invalidate(task.series.title);
    var filePath = path.join(task.options.output || '', title, persistenceName);
    fs.exists(filePath, function(exists) {
      if (!exists) {
        task.persistent = queue.save[filePath] = {};
        return enqueueSeriesNext(emitter, queue, task, done);
      }
      fs.readFile(filePath, 'utf8', function(err, contents) {
        if (err) return done(err);
        task.persistent = queue.save[filePath] = JSON.parse(contents);
        enqueueSeriesNext(emitter, queue, task, done);
      });
    });
  });
}

/**
 * Continues enqueuing the series.
 * @param {!IEmitter} emitter
 * @param {!Queue} queue
 * @param {!Object} task
 * @param {function(Error)} done
 */
function enqueueSeriesNext(emitter, queue, task, done) {
  shared.common.async.eachSeries(task.series.children, function(chapter, next) {
    if (!chapter) return next();
    enqueueChapter(emitter, queue, task, chapter, next);
  }, done);
}

/**
 * Saves each persistent record.
 * @param {!Object.<string, !Object>} records
 * @param {function(Error)} done
 */
function save(records, done) {
  shared.common.async.eachSeries(Object.keys(records), function(key, next) {
    var value = JSON.stringify(records[key], null, '  ');
    fs.writeFile(key, value, 'utf8', function() {
      // IGNORE: The error is ignored. While the error can be valid (due to
      // permissions, for example), it is considered likely to be the result of
      // attempting to write to a folder which has not been created by an agent.
      next();
    });
  }, done);
}

/**
 * Runs a chapter task.
 * @param {!EventEmitter} emitter
 * @param {!Object} task
 * @param {function(Error)} done
 */
function taskChapter(emitter, task, done) {
  var basename = path.basename(task.alias);
  var begin = Date.now();
  emitter.emit('data', {item: basename, type: 'fetching'});
  request(task.chapter, 'utf8', function(err) {
    if (err) return done(err);
    createAgent(task, function(err, agent) {
      if (err) return done(err);
      shared.publisher.mirror(agent, task.series, task.chapter, function(err) {
        if (err) return done(err);
        agent.publish(function(err) {
          if (err) return emitter.emit('error', err);
          if (!task.options.persistent) {
            task.persistent[task.chapter.identifier] = basename;
          }
          emitter.emit('data', {
            item: basename,
            timeInMs: Date.now() - begin,
            type: agent._disposed ? 'disposed' : 'finished'
          });
          done();
        });
      });
    });
  });
}

/**
 * Runs a series task.
 * @param {!EventEmitter} emitter
 * @param {!Queue} queue
 * @param {!Object} task
 * @param {function(Error)} done
 */
function taskSeries(emitter, queue, task, done) {
  task.series = shared.provider(task.address);
  if (task.series) return enqueueSeries(emitter, queue, task, done);
  emitter.emit('data', {item: task.address, type: 'obscured'});
  process.nextTick(done);
}
<|endoftext|>


<commit_before>const Boom = require( 'boom' ),
    Roles = require( '../../models.js' )
    .Roles;

module.exports = function checkRole( request, reply ) {

    let auth = request.route.settings.plugins.poetryAuth;

    process.nextTick( () => {

        // No auth check needed
        if ( !auth )
            return reply.continue();

        // Not logged on
        if ( !request.session.isAuthenticated || !request.session.user )
            return reply( Boom.unauthorized() );

        // SUPER case
        if ( request.session.user.role == 'SUPER' )
            return reply.continue();

        // ADMIN case
        if ( request.session.user.role == '*' )
            return roles( {
                name: "ADMIN",
                permissions: request.session.team.permissions
            } );

        // USER case
        let id;
        try {
            id = ObjectID( request.session.user.role );
        } catch ( err ) {
            Poetry.log.error( 'Wrong role for ', request.session.user );
            return reply( Boom.unauthorized() );
        }
        Roles.findOne( {
                _id: id,
                team: request.session.team._id
            } )
            .then( roles );

    } );

    function roles( role ) {

        if ( !role ) {
            Poetry.log.warn( 'Unknown role !', request.route.method, request.route.path );
            return reply( Boom.forbidden() );
        }

        // Special handwritten auths
        if ( Array.isArray( auth ) ) {
            let res = auth.some( tag => check(
                `API.${tag}.${ request.route.settings.description }`,
                role
            ) );

            if ( res === true )
                return reply.continue();
            if ( res === false )
                return reply( Boom.forbidden() );
        }

        if ( request.route.settings.tags ) {

            // For descripted routes
            if ( request.route.settings.description ) {

                let res = request.route.settings.tags.some( tag => check(
                    `API.${tag}.${ request.route.settings.description }`,
                    role
                ) );

                if ( res === true )
                    return reply.continue();
                if ( res === false )
                    return reply( Boom.forbidden() );
            }

            // For tagged routes
            let res = request.route.settings.tags.some( tag => check(
                `API.${tag}`,
                role
            ) );

            if ( res === true )
                return reply.continue();
            if ( res === false )
                return reply( Boom.forbidden() );

        }

        // FORBIDDEN
        Poetry.log.silly( 'No permission found', request.route.method, request.route.path );
        return reply( Boom.forbidden() );

    }

};

// Get nested value with dot notation
function check( path, object ) {

    path = path.split( '.' );

    // It's the targeted value
    if ( path.length == 1 )
        return object[ path[ 0 ] ];

    // Deep inspect sub object
    return check( path.slice( 1 )
        .join( '.' ), object[ path[ 0 ] ] );

}
<commit_msg>undefined<commit_after>const Boom = require( 'boom' ),
    Roles = require( '../../models.js' )
    .Roles;

module.exports = function checkRole( request, reply ) {

    let auth = request.route.settings.plugins.poetryAuth;

    process.nextTick( () => {

        // No auth check needed
        if ( !auth )
            return reply.continue();

        // Not logged on
        if ( !request.session.isAuthenticated || !request.session.user )
            return reply( Boom.unauthorized() );

        // SUPER case
        if ( request.session.user.role == 'SUPER' )
            return reply.continue();

        // ADMIN case
        if ( request.session.user.role == '*' )
            return roles( {
                name: "ADMIN",
                permissions: request.session.team.permissions
            } );

        // USER case
        let id;
        try {
            id = ObjectID( request.session.user.role );
        } catch ( err ) {
            Poetry.log.error( 'Wrong role for ', request.session.user );
            return reply( Boom.unauthorized() );
        }
        Roles.findOne( {
                _id: id,
                team: request.session.team._id
            } )
            .then( roles );

    } );

    function roles( role ) {

        if ( !role ) {
            Poetry.log.warn( 'Unknown role !', request.route.method, request.route.path );
            return reply( Boom.forbidden() );
        }

        // Special handwritten auths
        if ( Array.isArray( auth ) ) {
            let res = auth.some( tag => check(
                `API.${tag}.${ request.route.settings.description }`,
                role
            ) );

            if ( res === true )
                return reply.continue();
            if ( res === false )
                return reply( Boom.forbidden() );
        }

        if ( request.route.settings.tags ) {

            // For descripted routes
            if ( request.route.settings.description ) {

                let res = request.route.settings.tags.some( tag => check(
                    `API.${tag}.${ request.route.settings.description }`,
                    role
                ) );

                if ( res === true )
                    return reply.continue();
                if ( res === false )
                    return reply( Boom.forbidden() );
            }

            // For tagged routes
            let res = request.route.settings.tags.some( tag => check(
                `API.${tag}`,
                role
            ) );

            if ( res === true )
                return reply.continue();
            if ( res === false )
                return reply( Boom.forbidden() );

        }

        // FORBIDDEN
        Poetry.log.silly( 'No permission found', request.route.method, request.route.path );
        return reply( Boom.forbidden() );

    }

};

// Get nested value with dot notation
function check( path, object ) {

    path = path.split( '.' );
    if ( !object ) return undefined;
    if ( !object[ path[ 0 ] ] ) retunr undefined;

    // It's the targeted value
    if ( path.length == 1 )
        return object[ path[ 0 ] ];

    // Deep inspect sub object
    return check( path.slice( 1 )
        .join( '.' ), object[ path[ 0 ] ] );

}
<|endoftext|>


<commit_before>/*global window, require, console */
/*
 * panel.js
 *
 * Copyright (c) 2014 James G Jenner
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

// "use strict"

var node = false;

if (typeof module == "undefined") {
  var module = function () {};
  var exports = this.panel = {};
  module.exports = exports;
}
if (typeof require != "undefined") {
  var uuid = require('node-uuid');
}

module.exports = Panel;

Panel.KEY = 'Panel';

Panel.ICON_USER_DEFINED = 'userDefined';
Panel.ICON_FONT_AWESOME = 'fontAwesom';
Panel.ICON_GLYPHICON = 'glyphicon';
Panel.ICON_OPEN_ICONIC = 'openIconic';
Panel.ICON_ENTYPO = 'entypo';

Panel.DEFAULT_NAME = 'Panel Name';
Panel.DEFAULT_WIDTH = 1;
Panel.DEFAULT_ROW = 0;
Panel.DEFAULT_COLUMN = 1;
Panel.DEFAULT_ICON_TYPE = Panel.ICON_FONT_AWESOME;
Panel.DEFAULT_ICON_NAME = 'fa-group';

Panel.MESSAGE_ADD_PANEL = 'addPanel';
Panel.MESSAGE_DELETE_PANEL = 'deletePanel';
Panel.MESSAGE_UPDATE_PANEL = 'updatePanel';
Panel.MESSAGE_GET_PANELS = 'getPanels';
Panel.MESSAGE_PANELS = 'panels';

Panel.MESSAGE_MOVE_PANEL = 'movePanel';

Panel.MESSAGE_MOVE_PANEL_UP = 'movePanelUp';
Panel.MESSAGE_MOVE_PANEL_DOWN = 'movePanelDown';
Panel.MESSAGE_MOVE_PANEL_RIGHT = 'movePanelRight';
Panel.MESSAGE_MOVE_PANEL_LEFT = 'movePanelLeft';

function Panel(options) {
  options = options || {};

  var uuidV1 = ((options.uuidV1 !== null && options.uuidV1 !== undefined) ? options.uuidV1 : false);

  this.id = ((options.id !== null && options.id !== undefined) ? options.id : uuidV1 ? uuid.v1() : uuid.v4());
  this.name = ((options.name !== null && options.name !== undefined) ? options.name : Panel.DEFAULT_NAME);
  this.column = ((options.column !== null && options.column !== undefined) ? options.column : Panel.DEFAULT_COLUMN);
  this.width = ((options.width !== null && options.width !== undefined) ? options.width : Panel.DEFAULT_WIDTH);
  this.row = ((options.row !== null && options.row !== undefined) ? options.row : Panel.DEFAULT_ROW);
  this.iconName = ((options.iconName !== null && options.iconName !== undefined) ? options.iconName : Panel.DEFAULT_ICON_NAME);
  this.iconType = ((options.iconType !== null && options.iconType !== undefined) ? options.iconType : Panel.DEFAULT_ICON_TYPE);
}

/*
 * merge
 */
Panel.merge = function (d1, d2) {
  mergeAttribute(d1, d2, 'name');
  mergeAttribute(d1, d2, 'column');
  mergeAttribute(d1, d2, 'width');
  // TODO: sort out management of row value
  // mergeAttribute(d1, d2, 'row');
  mergeAttribute(d1, d2, 'iconName');
  mergeAttribute(d1, d2, 'iconType');
};

function mergeAttribute(object, modifiedObject, attribute) {
  object[attribute] = ((modifiedObject[attribute] !== null && modifiedObject[attribute] !== undefined) ? modifiedObject[attribute] : object[attribute]);
}<commit_msg>Added style<commit_after>/*global window, require, console */
/*
 * panel.js
 *
 * Copyright (c) 2014 James G Jenner
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

// "use strict"

var node = false;

if (typeof module == "undefined") {
  var module = function () {};
  var exports = this.panel = {};
  module.exports = exports;
}
if (typeof require != "undefined") {
  var uuid = require('node-uuid');
}

module.exports = Panel;

Panel.KEY = 'Panel';

Panel.ICON_USER_DEFINED = 'userDefined';
Panel.ICON_FONT_AWESOME = 'fontAwesom';
Panel.ICON_GLYPHICON = 'glyphicon';
Panel.ICON_OPEN_ICONIC = 'openIconic';
Panel.ICON_ENTYPO = 'entypo';

Panel.DEFAULT_NAME = 'Panel Name';
Panel.DEFAULT_WIDTH = 1;
Panel.DEFAULT_ROW = 0;
Panel.DEFAULT_COLUMN = 1;
Panel.DEFAULT_ICON_TYPE = Panel.ICON_FONT_AWESOME;
Panel.DEFAULT_ICON_NAME = 'fa-group';

Panel.MESSAGE_ADD_PANEL = 'addPanel';
Panel.MESSAGE_DELETE_PANEL = 'deletePanel';
Panel.MESSAGE_UPDATE_PANEL = 'updatePanel';
Panel.MESSAGE_GET_PANELS = 'getPanels';
Panel.MESSAGE_PANELS = 'panels';

Panel.MESSAGE_MOVE_PANEL = 'movePanel';

Panel.MESSAGE_MOVE_PANEL_UP = 'movePanelUp';
Panel.MESSAGE_MOVE_PANEL_DOWN = 'movePanelDown';
Panel.MESSAGE_MOVE_PANEL_RIGHT = 'movePanelRight';
Panel.MESSAGE_MOVE_PANEL_LEFT = 'movePanelLeft';

Panel.STYLE_NONE = 'None';
Panel.STYLE_AGILE = 'Agile';
Panel.STYLE_CI = 'CI Loop';

function Panel(options) {
  options = options || {};

  var uuidV1 = ((options.uuidV1 !== null && options.uuidV1 !== undefined) ? options.uuidV1 : false);

  this.id = ((options.id !== null && options.id !== undefined) ? options.id : uuidV1 ? uuid.v1() : uuid.v4());
  this.name = ((options.name !== null && options.name !== undefined) ? options.name : Panel.DEFAULT_NAME);
  this.column = ((options.column !== null && options.column !== undefined) ? options.column : Panel.DEFAULT_COLUMN);
  this.width = ((options.width !== null && options.width !== undefined) ? options.width : Panel.DEFAULT_WIDTH);
  this.row = ((options.row !== null && options.row !== undefined) ? options.row : Panel.DEFAULT_ROW);
  this.style = ((options.style !== null && options.style !== undefined) ? options.style : Panel.STYLE_NONE);
  this.iconName = ((options.iconName !== null && options.iconName !== undefined) ? options.iconName : Panel.DEFAULT_ICON_NAME);
  this.iconType = ((options.iconType !== null && options.iconType !== undefined) ? options.iconType : Panel.DEFAULT_ICON_TYPE);
}

/*
 * merge
 */
Panel.merge = function (d1, d2) {
  mergeAttribute(d1, d2, 'name');
  mergeAttribute(d1, d2, 'column');
  mergeAttribute(d1, d2, 'width');
  // TODO: sort out management of row value
  // mergeAttribute(d1, d2, 'row');
  mergeAttribute(d1, d2, 'style');
  mergeAttribute(d1, d2, 'iconName');
  mergeAttribute(d1, d2, 'iconType');
};

function mergeAttribute(object, modifiedObject, attribute) {
  object[attribute] = ((modifiedObject[attribute] !== null && modifiedObject[attribute] !== undefined) ? modifiedObject[attribute] : object[attribute]);
}<|endoftext|>