<commit_before>var express = require('express');
var router = express.Router();
var Product = require('../../../models/Product');
var crypto = require('crypto');
var async = require('async');
var passport = require('passport');
var nodemailer = require('nodemailer');
var jwt = require('jsonwebtoken');
var multer = require('multer');
var _ = require('lodash');
var secretmonster = 'meanstartedhahahaha';
var gm = require('gm').subClass({ imageMagick: true });

var storage = multer.diskStorage({
	destination: function (req, file, cb) {
		cb(null, 'public/uploads/'+req.decoded.user._id+'/products/c/')
	},
	filename: function (req, file, cb) {
		cb(null, new Date().getTime().toString() + '_' + file.fieldname + '-' + file.originalname)
	}
})
var upload = multer({ storage: storage });
var postImage = upload.fields([{name:'nProductImg1', maxCount:1}, {name:'nProductImg2', maxCount:1}, {name:'nProductImg3', maxCount:1}, {name:'nProductImg4', maxCount:1}])

router.get("/", function(req, res){
	Product.find({'store.id':req.decoded.user._id},{},{sort: '-createdOn'}, function(err, posts){
		if(err){
			response = {"success":false, "message":err};
		}else{
			response = {"success":true, "message":posts};
		}
		res.json(response);
	})
})

router.get("/get", function(req, res){
	Product.find({'store.id':req.decoded.user._id}, {'prodid':1, 'name':1}, {}, function(err, product){
		if(err){
			response = {"success":false, "message":err};
		}else{
			response = {"success":true, "message":product};
		}
		res.json(response);
	})
})

router.post('/add', postImage, function(req, res){

	// this needs refactoring!!!!
	var strProductImg1 = null
	var strProductImg2 = null
	var strProductImg3 = null
	var strProductImg4 = null

	// let's add image1
	if(req.files && req.files['nProductImg1'] && req.files['nProductImg1'][0] && req.files['nProductImg1'][0]['size']){
		strProductImg1 = req.files['nProductImg1'][0]['filename'];
	}

	// let's add image2
	if(req.files && req.files['nProductImg2'] && req.files['nProductImg2'][0] && req.files['nProductImg2'][0]['size']){
		strProductImg2 = req.files['nProductImg2'][0]['filename'];
	}

	// let's add image3
	if(req.files && req.files['nProductImg3'] && req.files['nProductImg3'][0] && req.files['nProductImg3'][0]['size']){
		strProductImg3 = req.files['nProductImg3'][0]['filename'];
	}

	// let's add image4
	if(req.files && req.files['nProductImg4'] && req.files['nProductImg4'][0] && req.files['nProductImg4'][0]['size']){
		strProductImg4 = req.files['nProductImg4'][0]['filename'];
	}

	async.forEachOfSeries([strProductImg1, strProductImg2, strProductImg3, strProductImg4], function(value, i, callback){
		if(value){
			var imgPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/c/"+value;
			var xsthumbPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/xs/"+value;
			var smthumbPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/sm/"+value;
			var mdthumbPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/md/"+value;

	 		async.series([
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('50', '50', "^>")
						.quality(70)
						.crop('50', '50')
						.write(xsthumbPath, function (err) {
							var msg = value + ' : c done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			},
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('50', '50', "^>")
						.quality(70)
						.crop('50', '50')
						.write(xsthumbPath, function (err) {
							var msg = value + ' : xs done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			},
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('200', '200', "^>")
						.quality(80)
						.crop('200', '200')
						.write(smthumbPath, function (err) {
							var msg = value + ' : sm done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			},
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('400', '400', "^>")
						.quality(90)
						.crop('400', '400')
						.write(mdthumbPath, function (err) {
							var msg = value + ' : md done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			}
	 		], function(err, result){
	 			console.log(result)
	 			callback()
	 		})
		}else{
			callback()
		}
	}, function(err){
		if(err){
			console.log(err)
		}else{
			console.log('DONE')
		}
	})

	console.log(req.body.tags)

	Product.create({
		name: req.body.name,
		desc: req.body.desc,
		price: req.body.price,
		image: req.files && req.files['images'] ? req.files['images'][0]['filename'] : 'none.jpg',
		images: {
			img1: strProductImg1,
			img2: strProductImg2,
			img3: strProductImg3,
			img4: strProductImg4
		},
		store: {
			id: req.decoded.user._id,
			name: req.decoded.user.store['name'],
			url: req.decoded.user.store['url']
		},
		category: {
			main: req.body.maincat,
			sub: req.body.subcat
		},
		sale: {
			off: req.body.saleOff,
			start: req.body.saleStart ? new Date(req.body.saleStart) : '',
			end: req.body.saleEnd ? new Date(req.body.saleEnd) : ''
		},
		tags: req.body.tags && JSON.parse(req.body.tags) ? JSON.parse(req.body.tags) : [],
		related: req.body.related && JSON.parse(req.body.related) ? JSON.parse(req.body.related) : []
	}, function(err, product){
		if(err){
			response = {"success":false, "message":err};
		}else{
			var prettyUrlRaw = req.body.name.trim()
				.replace(/ñ/g, 'n')
				.replace(/'/g, '')
				.replace(/"/g, '')
				.replace(/[^a-zA-Z0-9]/g,"")
				.toLowerCase()
				.replace(/--/g, '');

			Product.find({"urlraw":prettyUrlRaw, "_id": {$ne:product._id}}, {}, {sort: 'createdOn'}, function(err, products){
				var strPrettyUrl = prettyUrlRaw

				if(products.length > 0){
					strPrettyUrl = prettyUrlRaw + "-" + products.length;
				}

				product.url = strPrettyUrl;
				product.urlraw = prettyUrlRaw;
				product.save(function(err){
					if(err){
						console.log('unable to update store name', err)
					}
				})

			});

			response = {"success":true, "message":product};
		}
		res.json(response);
	});
});

router.get("/:id", function(req, res){
	Product.findById(req.params.id, function(err, product){
		if(err){
			response = {"success":false, "message":err};
		}else{
			response = {"success":true, "message":product};
		}
		res.json(response);
	})
})

router.put("/:id", postImage, function(req, res){

	// this needs refactoring!!!!
	var productImages = [];
	var imgs = [];

	var strProductImg1 = null
	var strProductImg2 = null
	var strProductImg3 = null
	var strProductImg4 = null

	// let's add image1
	if(req.files && req.files['nProductImg1'] && req.files['nProductImg1'][0] && req.files['nProductImg1'][0]['size']){
		strProductImg1 = req.files['nProductImg1'][0]['filename'];
	}
	if(!strProductImg1 && req.body.productImg1 != 'undefined'){
		strProductImg1 = req.body.productImg1;
	}

	// let's add image2
	if(req.files && req.files['nProductImg2'] && req.files['nProductImg2'][0] && req.files['nProductImg2'][0]['size']){
		strProductImg2 = req.files['nProductImg2'][0]['filename'];;
	}
	if(!strProductImg2 && req.body.productImg2 != 'undefined'){
		strProductImg2 = req.body.productImg2;
	}

	// let's add image3
	if(req.files && req.files['nProductImg3'] && req.files['nProductImg3'][0] && req.files['nProductImg3'][0]['size']){
		strProductImg3 = req.files['nProductImg3'][0]['filename'];
	}
	if(!strProductImg3 && req.body.productImg3 != 'undefined'){
		strProductImg3 = req.body.productImg;
	}

	// let's add image4
	if(req.files && req.files['nProductImg4'] && req.files['nProductImg4'][0] && req.files['nProductImg4'][0]['size']){
		strProductImg4 = req.files['nProductImg4'][0]['filename'];
	}
	if(!strProductImg4 && req.body.productImg4 != 'undefined'){
		strProductImg4 = req.body.productImg;
	}

	async.forEachOfSeries([strProductImg1, strProductImg2, strProductImg3, strProductImg4], function(value, i, callback){
		console.log(i, value)
		if(value != 'null' || value != 'undefined' || value != undefined || value != null){
			var imgPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/c/"+value;
			var xsthumbPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/xs/"+value;
			var smthumbPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/sm/"+value;
			var mdthumbPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/md/"+value;

	 		async.series([
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('50', '50', "^>")
						.quality(70)
						.crop('50', '50')
						.write(xsthumbPath, function (err) {
							var msg = value + ' : c done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			},
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('50', '50', "^>")
						.quality(70)
						.crop('50', '50')
						.write(xsthumbPath, function (err) {
							var msg = value + ' : xs done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			},
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('200', '200', "^>")
						.quality(80)
						.crop('200', '200')
						.write(smthumbPath, function (err) {
							var msg = value + ' : sm done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			},
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('400', '400', "^>")
						.quality(90)
						.crop('400', '400')
						.write(mdthumbPath, function (err) {
							var msg = value + ' : md done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			}
	 		], function(err, result){
	 			console.log(result)
	 			callback()
	 		})
		}
	}, function(err){
		if(err){
			console.log(err)
		}else{
			console.log('DONE')
		}
	})

	Product.findById(req.params.id, function(err, post){
		if(err){
			res.json({"success":false, "message":err});
		}else{
			post.name = req.body.name;
			post.desc = req.body.desc;
			post.price = req.body.price;
			post.images = {
				img1: strProductImg1,
				img2: strProductImg2,
				img3: strProductImg3,
				img4: strProductImg4
			};
			post.category = {
				main: req.body.maincat,
				sub: req.body.subcat
			};

			post.tags = req.body.tags && JSON.parse(req.body.tags) ? JSON.parse(req.body.tags) : [];
			post.related = req.body.related && JSON.parse(req.body.related) ? JSON.parse(req.body.related) : [];

			post.save(function(err) {
                if(err){
                	response = {"success":true, "message":err};
                }else{
                	response = {"success":true, "message":post};
                }
                res.json(response);
            });
		}
	})
})

router.delete("/:id", function(req, res){
	Product.remove({
		_id:req.params.id
	}, function(err, post){
		if(err){
			res.json({"success":false, "message":err});
		}else{
			response = {"success":true, "message":"Product was deleted successfully"};
		}
        res.json(response);
	});
})

module.exports = router;
<commit_msg>verify this<commit_after>var express = require('express');
var router = express.Router();
var Product = require('../../../models/Product');
var crypto = require('crypto');
var async = require('async');
var passport = require('passport');
var nodemailer = require('nodemailer');
var jwt = require('jsonwebtoken');
var multer = require('multer');
var _ = require('lodash');
var secretmonster = 'meanstartedhahahaha';
var gm = require('gm').subClass({ imageMagick: true });

var storage = multer.diskStorage({
	destination: function (req, file, cb) {
		cb(null, 'public/uploads/'+req.decoded.user._id+'/products/c/')
	},
	filename: function (req, file, cb) {
		cb(null, new Date().getTime().toString() + '_' + file.fieldname + '-' + file.originalname)
	}
})
var upload = multer({ storage: storage });
var postImage = upload.fields([{name:'nProductImg1', maxCount:1}, {name:'nProductImg2', maxCount:1}, {name:'nProductImg3', maxCount:1}, {name:'nProductImg4', maxCount:1}])

router.get("/", function(req, res){
	Product.find({'store.id':req.decoded.user._id},{},{sort: '-createdOn'}, function(err, posts){
		if(err){
			response = {"success":false, "message":err};
		}else{
			response = {"success":true, "message":posts};
		}
		res.json(response);
	})
})

router.get("/get", function(req, res){
	Product.find({'store.id':req.decoded.user._id}, {'prodid':1, 'name':1}, {}, function(err, product){
		if(err){
			response = {"success":false, "message":err};
		}else{
			response = {"success":true, "message":product};
		}
		res.json(response);
	})
})

router.post('/add', postImage, function(req, res){

	// this needs refactoring!!!!
	var strProductImg1 = null
	var strProductImg2 = null
	var strProductImg3 = null
	var strProductImg4 = null

	// let's add image1
	if(req.files && req.files['nProductImg1'] && req.files['nProductImg1'][0] && req.files['nProductImg1'][0]['size']){
		strProductImg1 = req.files['nProductImg1'][0]['filename'];
	}

	// let's add image2
	if(req.files && req.files['nProductImg2'] && req.files['nProductImg2'][0] && req.files['nProductImg2'][0]['size']){
		strProductImg2 = req.files['nProductImg2'][0]['filename'];
	}

	// let's add image3
	if(req.files && req.files['nProductImg3'] && req.files['nProductImg3'][0] && req.files['nProductImg3'][0]['size']){
		strProductImg3 = req.files['nProductImg3'][0]['filename'];
	}

	// let's add image4
	if(req.files && req.files['nProductImg4'] && req.files['nProductImg4'][0] && req.files['nProductImg4'][0]['size']){
		strProductImg4 = req.files['nProductImg4'][0]['filename'];
	}

	async.forEachOfSeries([strProductImg1, strProductImg2, strProductImg3, strProductImg4], function(value, i, callback){
		if(value){
			var imgPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/c/"+value;
			var xsthumbPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/xs/"+value;
			var smthumbPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/sm/"+value;
			var mdthumbPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/md/"+value;

	 		async.series([
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('50', '50', "^>")
						.quality(70)
						.crop('50', '50')
						.write(xsthumbPath, function (err) {
							var msg = value + ' : c done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			},
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('50', '50', "^>")
						.quality(70)
						.crop('50', '50')
						.write(xsthumbPath, function (err) {
							var msg = value + ' : xs done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			},
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('200', '200', "^>")
						.quality(80)
						.crop('200', '200')
						.write(smthumbPath, function (err) {
							var msg = value + ' : sm done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			},
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('400', '400', "^>")
						.quality(90)
						.crop('400', '400')
						.write(mdthumbPath, function (err) {
							var msg = value + ' : md done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			}
	 		], function(err, result){
	 			console.log(result)
	 			callback()
	 		})
		}else{
			callback()
		}
	}, function(err){
		if(err){
			console.log(err)
		}else{
			console.log('DONE')
		}
	})

	console.log(req.body.tags)

	Product.create({
		name: req.body.name,
		desc: req.body.desc,
		price: req.body.price,
		image: req.files && req.files['images'] ? req.files['images'][0]['filename'] : 'none.jpg',
		images: {
			img1: strProductImg1,
			img2: strProductImg2,
			img3: strProductImg3,
			img4: strProductImg4
		},
		store: {
			id: req.decoded.user._id,
			name: req.decoded.user.store['name'],
			url: req.decoded.user.store['url']
		},
		category: {
			main: req.body.maincat,
			sub: req.body.subcat
		},
		sale: {
			off: req.body.saleOff,
			start: req.body.saleStart ? new Date(req.body.saleStart) : '',
			end: req.body.saleEnd ? new Date(req.body.saleEnd) : ''
		},
		tags: req.body.tags && JSON.parse(req.body.tags) ? JSON.parse(req.body.tags) : [],
		related: req.body.related && JSON.parse(req.body.related) ? JSON.parse(req.body.related) : []
	}, function(err, product){
		if(err){
			response = {"success":false, "message":err};
		}else{
			var prettyUrlRaw = req.body.name.trim()
				.replace(/ñ/g, 'n')
				.replace(/'/g, '')
				.replace(/"/g, '')
				.replace(/[^a-zA-Z0-9]/g,"")
				.toLowerCase()
				.replace(/--/g, '');

			Product.find({"urlraw":prettyUrlRaw, "_id": {$ne:product._id}}, {}, {sort: 'createdOn'}, function(err, products){
				var strPrettyUrl = prettyUrlRaw

				if(products.length > 0){
					strPrettyUrl = prettyUrlRaw + "-" + products.length;
				}

				product.url = strPrettyUrl;
				product.urlraw = prettyUrlRaw;
				product.save(function(err){
					if(err){
						console.log('unable to update store name', err)
					}
				})

			});

			response = {"success":true, "message":product};
		}
		res.json(response);
	});
});

router.get("/:id", function(req, res){
	Product.findById(req.params.id, function(err, product){
		if(err){
			response = {"success":false, "message":err};
		}else{
			response = {"success":true, "message":product};
		}
		res.json(response);
	})
})

router.put("/:id", postImage, function(req, res){

	// this needs refactoring!!!!
	var productImages = [];
	var imgs = [];

	var strProductImg1 = null
	var strProductImg2 = null
	var strProductImg3 = null
	var strProductImg4 = null

	var

	// let's add image1
	if(req.files && req.files['nProductImg1'] && req.files['nProductImg1'][0] && req.files['nProductImg1'][0]['size']){
		strProductImg1 = req.files['nProductImg1'][0]['filename'];
	}
	if(!strProductImg1 && req.body.productImg1 != 'undefined'){
		strProductImg1 = req.body.productImg1;
	}

	// let's add image2
	if(req.files && req.files['nProductImg2'] && req.files['nProductImg2'][0] && req.files['nProductImg2'][0]['size']){
		strProductImg2 = req.files['nProductImg2'][0]['filename'];;
	}
	if(!strProductImg2 && req.body.productImg2 != 'undefined'){
		strProductImg2 = req.body.productImg2;
	}

	// let's add image3
	if(req.files && req.files['nProductImg3'] && req.files['nProductImg3'][0] && req.files['nProductImg3'][0]['size']){
		strProductImg3 = req.files['nProductImg3'][0]['filename'];
	}
	if(!strProductImg3 && req.body.productImg3 != 'undefined'){
		strProductImg3 = req.body.productImg;
	}

	// let's add image4
	if(req.files && req.files['nProductImg4'] && req.files['nProductImg4'][0] && req.files['nProductImg4'][0]['size']){
		strProductImg4 = req.files['nProductImg4'][0]['filename'];
	}
	if(!strProductImg4 && req.body.productImg4 != 'undefined'){
		strProductImg4 = req.body.productImg;
	}

	async.forEachOfSeries([strProductImg1, strProductImg2, strProductImg3, strProductImg4], function(value, i, callback){
		console.log(i, value)
		if(value != 'null' || value != 'undefined' || value != undefined || value != null){
			var imgPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/c/"+value;
			var xsthumbPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/xs/"+value;
			var smthumbPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/sm/"+value;
			var mdthumbPath = __dirname + "/../../../public/uploads/"+req.decoded.user._id+"/products/md/"+value;

	 		async.series([
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('50', '50', "^>")
						.quality(70)
						.crop('50', '50')
						.write(xsthumbPath, function (err) {
							var msg = value + ' : c done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			},
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('50', '50', "^>")
						.quality(70)
						.crop('50', '50')
						.write(xsthumbPath, function (err) {
							var msg = value + ' : xs done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			},
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('200', '200', "^>")
						.quality(80)
						.crop('200', '200')
						.write(smthumbPath, function (err) {
							var msg = value + ' : sm done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			},
	 			function(cb){
	 				gm(imgPath)
						.noProfile()
						.gravity('center')
						.resize('400', '400', "^>")
						.quality(90)
						.crop('400', '400')
						.write(mdthumbPath, function (err) {
							var msg = value + ' : md done';
							if (err){
								msg = err
							}
							cb(null, msg);
						});
	 			}
	 		], function(err, result){
	 			console.log(result)
	 			callback()
	 		})
		}
	}, function(err){
		if(err){
			console.log(err)
		}else{
			console.log('DONE')
		}
	})

	Product.findById(req.params.id, function(err, post){
		if(err){
			res.json({"success":false, "message":err});
		}else{
			post.name = req.body.name;
			post.desc = req.body.desc;
			post.price = req.body.price;
			post.images = {
				img1: strProductImg1,
				img2: strProductImg2,
				img3: strProductImg3,
				img4: strProductImg4
			};
			post.category = {
				main: req.body.maincat,
				sub: req.body.subcat
			};

			post.tags = req.body.tags && JSON.parse(req.body.tags) ? JSON.parse(req.body.tags) : [];
			post.related = req.body.related && JSON.parse(req.body.related) ? JSON.parse(req.body.related) : [];

			post.save(function(err) {
                if(err){
                	response = {"success":true, "message":err};
                }else{
                	response = {"success":true, "message":post};
                }
                res.json(response);
            });
		}
	})
})

router.delete("/:id", function(req, res){
	Product.remove({
		_id:req.params.id
	}, function(err, post){
		if(err){
			res.json({"success":false, "message":err});
		}else{
			response = {"success":true, "message":"Product was deleted successfully"};
		}
        res.json(response);
	});
})

module.exports = router;
<|endoftext|>


<commit_before>'use';

var Suite = require('benchmarked');
var suite = new Suite({
  code: 'code/*.js',
  fixtures: 'fixtures/*.js',
  cwd: __dirname
});

suite.run();<commit_msg>fix benchmark<commit_after>'use';

var Suite = require('benchmarked');
var suite = new Suite({
  add: 'code/*.js',
  fixtures: 'fixtures/*.js',
  cwd: __dirname
});

suite.run();
<|endoftext|>


<commit_before>/*
 * Copyright 2017 Scott Bender <scott@scottbender.net>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

const debug = require('debug')('signalk:interfaces:appstore')
const _ = require('lodash')
const fs = require('fs')
const compareVersions = require('compare-versions')
const path = require('path')
const installModule = require('../modules').installModule
const findModulesWithKeyword = require('../modules').findModulesWithKeyword
const page = require('../page')

module.exports = function (app) {
  var moduleInstalling = undefined
  var modulesInstalledSinceStartup = {}
  var moduleInstallQueue = []

  return {
    start: function () {
      app.get('/appstore/output/:id/:version', (req, res, next) => {
        let { result, footer } = page(__dirname + '/appstore.html')

        result += '
Errors installing ' + req.params.id + '
'
        result += '
'
        result += modulesInstalledSinceStartup[req.params.id].output
        result += '
'
        result +=
          '<button type="button" class="btn">Retry</button> '
        result += footer
        res.send(result)
      })

      app.post(
        [
          '/appstore/install/:name/:version',
          '/appstore/install/:org/:name/:version'
        ],
        (req, res, next) => {
          var name = req.params.name
          var version = req.params.version

          if (req.params.org) {
            name = req.params.org + '/' + name
          }

          findPluginsAndWebapps()
            .then(([plugins, webapps]) => {
              if (
                !plugins.find(packageNameIs(name)) &&
                !webapps.find(packageNameIs(name))
              ) {
                res.status(404)
                res.send('No such webapp or plugin available:' + name)
              } else {
                if (moduleInstalling) {
                  moduleInstallQueue.push({ name: name, version: version })
                  sendAppStoreChangedEvent()
                } else {
                  installSKModule(name, version)
                }
                res.send(`Installing ${name}...`)
              }
            })
            .catch(error => {
              console.error(error.message)
              console.error(error.stack)
              res.status(500)
              res.send('
' + error.message + '
')
            })
        }
      )

      app.get('/appstore/available/', (req, res, next) => {
        findPluginsAndWebapps()
          .then(([plugins, webapps]) => {
            var result = getAllModuleInfo(plugins, webapps)
            res.send(JSON.stringify(result))
          })
          .catch(error => {
            if (error.code === 'ENOTFOUND') {
              res.send({
                available: [],
                installed: [],
                updates: [],
                installing: [],
                storeAvailable: false
              })
            }
            console.log(error)
            console.error(error.message)
            console.error(error.stack)
            res.status(500)
            res.send(error.message)
          })
      })

      app.get('/appstore/', (req, res, next) => {
        let { result, footer } = page(__dirname + '/appstore.html')

        findPluginsAndWebapps()
          .then(([plugins, webapps]) => {
            if (Object.keys(modulesInstalledSinceStartup).length) {
              result += '
Server '
              if (
                moduleInstallQueue.length > 0 ||
                moduleInstalling ||
                !app.securityStrategy
              ) {
                result += 'restart'
              } else {
                result += 'restart'
              }
              result +=
                ' is required to finish install or update of plugins and web apps.
\n'
            }

            result += makeSection(
              'Plugins',
              plugins,
              getPlugin,
              '/plugins/configure/#'
            )
            result += makeSection('Web Apps', webapps, getWebApp, '')

            if (moduleInstalling) {
              result +=
                ''
            }

            result += footer
            res.send(result)
          })
          .catch(error => {
            console.error(error.message)
            console.error(error.stack)
            res.status(500)
            res.send('
' + error.message + '
')
          })
      })
    },
    stop: function () {}
  }

  function findPluginsAndWebapps () {
    return Promise.all([
      findModulesWithKeyword('signalk-node-server-plugin'),
      findModulesWithKeyword('signalk-webapp')
    ])
  }

  function getPlugin (id) {
    return app.plugins.find(plugin => plugin.packageName === id)
  }

  function getWebApp (id) {
    return app.webapps.find(webapp => webapp.name === id)
  }

  function getAllModuleInfo (plugins, webapps) {
    var all = {
      available: [],
      installed: [],
      updates: [],
      installing: [],
      storeAvailable: true
    }

    getModulesInfo(plugins, getPlugin, all)
    getModulesInfo(webapps, getWebApp, all)
    return all
  }

  function getModulesInfo (modules, existing, result) {
    modules.forEach(plugin => {
      var name = plugin.package.name
      var version = plugin.package.version

      var pluginInfo = {
        name: name,
        version: version,
        description: plugin.package.description,
        author: getAuthor(plugin),
        npmUrl: getNpmUrl(plugin),
        isPlugin: plugin.package.keywords.some(
          v => v === 'signalk-node-server-plugin'
        ),
        isWebapp: plugin.package.keywords.some(v => v === 'signalk-webapp')
      }

      var installedModule = existing(name)

      if (installedModule) {
        pluginInfo.installedVersion = installedModule.version
      }

      if (moduleInstallQueue.find(p => p.name == name)) {
        pluginInfo.isWaiting = true
        result.installing.push(pluginInfo)
      } else if (modulesInstalledSinceStartup[name]) {
        if (moduleInstalling && moduleInstalling.name == name) {
          pluginInfo.isInstalling = true
        } else if (modulesInstalledSinceStartup[name].code != 0) {
          pluginInfo.installFailed = true
        }
        result.installing.push(pluginInfo)
      } else if (installedModule) {
        if (compareVersions(version, installedModule.version) > 0) {
          result.updates.push(pluginInfo)
        } else {
          result.installed.push(pluginInfo)
        }
      } else {
        result.available.push(pluginInfo)
      }

      return result
    })
  }

  function makeSection (title, modules, existing, pathPrefix) {
    modules = modules.sort((left, right) => {
      if (pathPrefix + left.package.name < pathPrefix + right.package.name) {
        return -1
      } else if (
        pathPrefix + left.package.name >
        pathPrefix + right.package.name
      ) {
        return 1
      } else {
        return 0
      }
    })
    return `

${title}

        Install
        Update
        Name
        Description
        Authors
        Link

      ${makeRows(modules, existing, pathPrefix)}

    `
  }

  function makeRows (modules, existing, pathPrefix) {
    return modules.reduce(function (result, moduleInfo) {
      var name = moduleInfo.package.name
      var version = moduleInfo.package.version

      var installedModule = existing(name)
      var isLink = false
      if (installedModule) {
        var stat = fs.lstatSync(
          path.join(__dirname, '../../node_modules/' + name)
        )
        var isLink = stat.isSymbolicLink()
      }

      result += `

          ${getInstallColumn(name, version, installedModule, isLink)}
          ${getUpdateColumn(name, version, installedModule, isLink)}
          ${getNameColumn(name, installedModule, pathPrefix)}
          ${moduleInfo.package.description}
          ${getAuthorColumn(moduleInfo)}
          ${getNpmColumn(moduleInfo)}

      `
      return result
    }, '')
  }

  function getNameColumn (name, installedModule, pathPrefix) {
    return installedModule
      ? `<a href="${pathPrefix}${name}">${name}</a>`
      : `${name}`
  }

  function getAuthorColumn (moduleInfo) {
    debug(moduleInfo.package.name + ' author: ' + moduleInfo.package.author)
    return (
      (moduleInfo.package.author &&
        (moduleInfo.package.author.name || moduleInfo.package.author.email)) +
      '' +
      (moduleInfo.package.contributors || [])
        .map(contributor => contributor.name || contributor.email)
        .join(',') +
      '' +
      (moduleInfo.package.name.startsWith('@signalk/')
        ? ' (Signal K team)'
        : '')
    )
  }

  function getAuthor (moduleInfo) {
    debug(moduleInfo.package.name + ' author: ' + moduleInfo.package.author)
    return (
      (moduleInfo.package.author &&
        (moduleInfo.package.author.name || moduleInfo.package.author.email)) +
      '' +
      (moduleInfo.package.contributors || [])
        .map(contributor => contributor.name || contributor.email)
        .join(',') +
      '' +
      (moduleInfo.package.name.startsWith('@signalk/')
        ? ' (Signal K team)'
        : '')
    )
  }

  function getNpmColumn (moduleInfo) {
    const npm = _.get(moduleInfo.package, 'links.npm')
    return npm ? 'npm' : ''
  }

  function getNpmUrl (moduleInfo) {
    const npm = _.get(moduleInfo.package, 'links.npm')
    return npm || null
  }

  function getInstallColumn (name, version, installedModule, isLink) {
    let result = ''
    if (modulesInstalledSinceStartup[name]) {
      if (moduleInstalling && moduleInstalling.name == name) {
        result += `
Installing ${
          moduleInstalling.version
        }...
`
      } else if (modulesInstalledSinceStartup[name].code == 0) {
        result += `
 Installed ${
          modulesInstalledSinceStartup[name].version
        }
`
      } else {
        result += `

          <button type="button" class="btn-danger">Error</button>
          `
      }
    } else if (moduleInstallQueue.find(p => p.name == name)) {
      result += '
Waiting...
'
    } else if (!installedModule) {
      result += `<a href="/appstore/install/${name}/${version}"><button type="button" class="btn">Install ${version}</button></a>`
    } else {
      result += `${installedModule.version} Installed`
      if (isLink) {
        result += '
(Linked)' + '
'
      }
    }
    return result
  }

  function getUpdateColumn (name, version, installedModule, isLink) {
    let result = ''
    if (!modulesInstalledSinceStartup[name]) {
      if (installedModule) {
        var compared = compareVersions(version, installedModule.version)
        if (compared > 0) {
          if (!isLink) {
            result += `

            <button type="button" class="btn">Update to ${version}</button>
            `
          } else {
            result += version
          }
        } else if (compared < 0) {
          result += 'Newer Installed'
        } else {
          result += 'Latest Installed'
        }
      }
    }
    return result
  }

  function sendAppStoreChangedEvent () {
    findPluginsAndWebapps().then(([plugins, webapps]) => {
      var result = getAllModuleInfo(plugins, webapps)
      app.emit('serverevent', {
        type: 'APP_STORE_CHANGED',
        from: 'signalk-server',
        data: result
      })
    })
  }

  function installSKModule (module, version) {
    moduleInstalling = {
      name: module,
      output: [],
      version: version
    }
    modulesInstalledSinceStartup[module] = moduleInstalling

    sendAppStoreChangedEvent()

    installModule(
      app,
      module,
      version,
      output => {
        modulesInstalledSinceStartup[module].output.push(output)
        console.log(`stdout: ${output}`)
      },
      output => {
        modulesInstalledSinceStartup[module].output.push(output)
        console.error(`stderr: ${output}`)
      },
      code => {
        debug('close: ' + module)
        modulesInstalledSinceStartup[module]['code'] = code
        moduleInstalling = undefined
        console.log(`child process exited with code ${code}`)

        if (moduleInstallQueue.length) {
          var next = moduleInstallQueue.splice(0, 1)[0]
          installSKModule(next.name, next.version)
        }

        sendAppStoreChangedEvent()
      }
    )
  }
}

function packageNameIs (name) {
  return x => x.package.name === name
}
<commit_msg>chore: change log to debug<commit_after>/*
 * Copyright 2017 Scott Bender <scott@scottbender.net>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

const debug = require('debug')('signalk:interfaces:appstore')
const _ = require('lodash')
const fs = require('fs')
const compareVersions = require('compare-versions')
const path = require('path')
const installModule = require('../modules').installModule
const findModulesWithKeyword = require('../modules').findModulesWithKeyword
const page = require('../page')

module.exports = function (app) {
  var moduleInstalling = undefined
  var modulesInstalledSinceStartup = {}
  var moduleInstallQueue = []

  return {
    start: function () {
      app.get('/appstore/output/:id/:version', (req, res, next) => {
        let { result, footer } = page(__dirname + '/appstore.html')

        result += '
Errors installing ' + req.params.id + '
'
        result += '
'
        result += modulesInstalledSinceStartup[req.params.id].output
        result += '
'
        result +=
          '<button type="button" class="btn">Retry</button> '
        result += footer
        res.send(result)
      })

      app.post(
        [
          '/appstore/install/:name/:version',
          '/appstore/install/:org/:name/:version'
        ],
        (req, res, next) => {
          var name = req.params.name
          var version = req.params.version

          if (req.params.org) {
            name = req.params.org + '/' + name
          }

          findPluginsAndWebapps()
            .then(([plugins, webapps]) => {
              if (
                !plugins.find(packageNameIs(name)) &&
                !webapps.find(packageNameIs(name))
              ) {
                res.status(404)
                res.send('No such webapp or plugin available:' + name)
              } else {
                if (moduleInstalling) {
                  moduleInstallQueue.push({ name: name, version: version })
                  sendAppStoreChangedEvent()
                } else {
                  installSKModule(name, version)
                }
                res.send(`Installing ${name}...`)
              }
            })
            .catch(error => {
              console.error(error.message)
              console.error(error.stack)
              res.status(500)
              res.send('
' + error.message + '
')
            })
        }
      )

      app.get('/appstore/available/', (req, res, next) => {
        findPluginsAndWebapps()
          .then(([plugins, webapps]) => {
            var result = getAllModuleInfo(plugins, webapps)
            res.send(JSON.stringify(result))
          })
          .catch(error => {
            if (error.code === 'ENOTFOUND') {
              res.send({
                available: [],
                installed: [],
                updates: [],
                installing: [],
                storeAvailable: false
              })
            }
            console.log(error)
            console.error(error.message)
            console.error(error.stack)
            res.status(500)
            res.send(error.message)
          })
      })

      app.get('/appstore/', (req, res, next) => {
        let { result, footer } = page(__dirname + '/appstore.html')

        findPluginsAndWebapps()
          .then(([plugins, webapps]) => {
            if (Object.keys(modulesInstalledSinceStartup).length) {
              result += '
Server '
              if (
                moduleInstallQueue.length > 0 ||
                moduleInstalling ||
                !app.securityStrategy
              ) {
                result += 'restart'
              } else {
                result += 'restart'
              }
              result +=
                ' is required to finish install or update of plugins and web apps.
\n'
            }

            result += makeSection(
              'Plugins',
              plugins,
              getPlugin,
              '/plugins/configure/#'
            )
            result += makeSection('Web Apps', webapps, getWebApp, '')

            if (moduleInstalling) {
              result +=
                ''
            }

            result += footer
            res.send(result)
          })
          .catch(error => {
            console.error(error.message)
            console.error(error.stack)
            res.status(500)
            res.send('
' + error.message + '
')
          })
      })
    },
    stop: function () {}
  }

  function findPluginsAndWebapps () {
    return Promise.all([
      findModulesWithKeyword('signalk-node-server-plugin'),
      findModulesWithKeyword('signalk-webapp')
    ])
  }

  function getPlugin (id) {
    return app.plugins.find(plugin => plugin.packageName === id)
  }

  function getWebApp (id) {
    return app.webapps.find(webapp => webapp.name === id)
  }

  function getAllModuleInfo (plugins, webapps) {
    var all = {
      available: [],
      installed: [],
      updates: [],
      installing: [],
      storeAvailable: true
    }

    getModulesInfo(plugins, getPlugin, all)
    getModulesInfo(webapps, getWebApp, all)
    return all
  }

  function getModulesInfo (modules, existing, result) {
    modules.forEach(plugin => {
      var name = plugin.package.name
      var version = plugin.package.version

      var pluginInfo = {
        name: name,
        version: version,
        description: plugin.package.description,
        author: getAuthor(plugin),
        npmUrl: getNpmUrl(plugin),
        isPlugin: plugin.package.keywords.some(
          v => v === 'signalk-node-server-plugin'
        ),
        isWebapp: plugin.package.keywords.some(v => v === 'signalk-webapp')
      }

      var installedModule = existing(name)

      if (installedModule) {
        pluginInfo.installedVersion = installedModule.version
      }

      if (moduleInstallQueue.find(p => p.name == name)) {
        pluginInfo.isWaiting = true
        result.installing.push(pluginInfo)
      } else if (modulesInstalledSinceStartup[name]) {
        if (moduleInstalling && moduleInstalling.name == name) {
          pluginInfo.isInstalling = true
        } else if (modulesInstalledSinceStartup[name].code != 0) {
          pluginInfo.installFailed = true
        }
        result.installing.push(pluginInfo)
      } else if (installedModule) {
        if (compareVersions(version, installedModule.version) > 0) {
          result.updates.push(pluginInfo)
        } else {
          result.installed.push(pluginInfo)
        }
      } else {
        result.available.push(pluginInfo)
      }

      return result
    })
  }

  function makeSection (title, modules, existing, pathPrefix) {
    modules = modules.sort((left, right) => {
      if (pathPrefix + left.package.name < pathPrefix + right.package.name) {
        return -1
      } else if (
        pathPrefix + left.package.name >
        pathPrefix + right.package.name
      ) {
        return 1
      } else {
        return 0
      }
    })
    return `

${title}

        Install
        Update
        Name
        Description
        Authors
        Link

      ${makeRows(modules, existing, pathPrefix)}

    `
  }

  function makeRows (modules, existing, pathPrefix) {
    return modules.reduce(function (result, moduleInfo) {
      var name = moduleInfo.package.name
      var version = moduleInfo.package.version

      var installedModule = existing(name)
      var isLink = false
      if (installedModule) {
        var stat = fs.lstatSync(
          path.join(__dirname, '../../node_modules/' + name)
        )
        var isLink = stat.isSymbolicLink()
      }

      result += `

          ${getInstallColumn(name, version, installedModule, isLink)}
          ${getUpdateColumn(name, version, installedModule, isLink)}
          ${getNameColumn(name, installedModule, pathPrefix)}
          ${moduleInfo.package.description}
          ${getAuthorColumn(moduleInfo)}
          ${getNpmColumn(moduleInfo)}

      `
      return result
    }, '')
  }

  function getNameColumn (name, installedModule, pathPrefix) {
    return installedModule
      ? `<a href="${pathPrefix}${name}">${name}</a>`
      : `${name}`
  }

  function getAuthorColumn (moduleInfo) {
    debug(moduleInfo.package.name + ' author: ' + moduleInfo.package.author)
    return (
      (moduleInfo.package.author &&
        (moduleInfo.package.author.name || moduleInfo.package.author.email)) +
      '' +
      (moduleInfo.package.contributors || [])
        .map(contributor => contributor.name || contributor.email)
        .join(',') +
      '' +
      (moduleInfo.package.name.startsWith('@signalk/')
        ? ' (Signal K team)'
        : '')
    )
  }

  function getAuthor (moduleInfo) {
    debug(moduleInfo.package.name + ' author: ' + moduleInfo.package.author)
    return (
      (moduleInfo.package.author &&
        (moduleInfo.package.author.name || moduleInfo.package.author.email)) +
      '' +
      (moduleInfo.package.contributors || [])
        .map(contributor => contributor.name || contributor.email)
        .join(',') +
      '' +
      (moduleInfo.package.name.startsWith('@signalk/')
        ? ' (Signal K team)'
        : '')
    )
  }

  function getNpmColumn (moduleInfo) {
    const npm = _.get(moduleInfo.package, 'links.npm')
    return npm ? 'npm' : ''
  }

  function getNpmUrl (moduleInfo) {
    const npm = _.get(moduleInfo.package, 'links.npm')
    return npm || null
  }

  function getInstallColumn (name, version, installedModule, isLink) {
    let result = ''
    if (modulesInstalledSinceStartup[name]) {
      if (moduleInstalling && moduleInstalling.name == name) {
        result += `
Installing ${
          moduleInstalling.version
        }...
`
      } else if (modulesInstalledSinceStartup[name].code == 0) {
        result += `
 Installed ${
          modulesInstalledSinceStartup[name].version
        }
`
      } else {
        result += `

          <button type="button" class="btn-danger">Error</button>
          `
      }
    } else if (moduleInstallQueue.find(p => p.name == name)) {
      result += '
Waiting...
'
    } else if (!installedModule) {
      result += `<a href="/appstore/install/${name}/${version}"><button type="button" class="btn">Install ${version}</button></a>`
    } else {
      result += `${installedModule.version} Installed`
      if (isLink) {
        result += '
(Linked)' + '
'
      }
    }
    return result
  }

  function getUpdateColumn (name, version, installedModule, isLink) {
    let result = ''
    if (!modulesInstalledSinceStartup[name]) {
      if (installedModule) {
        var compared = compareVersions(version, installedModule.version)
        if (compared > 0) {
          if (!isLink) {
            result += `

            <button type="button" class="btn">Update to ${version}</button>
            `
          } else {
            result += version
          }
        } else if (compared < 0) {
          result += 'Newer Installed'
        } else {
          result += 'Latest Installed'
        }
      }
    }
    return result
  }

  function sendAppStoreChangedEvent () {
    findPluginsAndWebapps().then(([plugins, webapps]) => {
      var result = getAllModuleInfo(plugins, webapps)
      app.emit('serverevent', {
        type: 'APP_STORE_CHANGED',
        from: 'signalk-server',
        data: result
      })
    })
  }

  function installSKModule (module, version) {
    moduleInstalling = {
      name: module,
      output: [],
      version: version
    }
    modulesInstalledSinceStartup[module] = moduleInstalling

    sendAppStoreChangedEvent()

    installModule(
      app,
      module,
      version,
      output => {
        modulesInstalledSinceStartup[module].output.push(output)
        console.log(`stdout: ${output}`)
      },
      output => {
        modulesInstalledSinceStartup[module].output.push(output)
        console.error(`stderr: ${output}`)
      },
      code => {
        debug('close: ' + module)
        modulesInstalledSinceStartup[module]['code'] = code
        moduleInstalling = undefined
        debug(`child process exited with code ${code}`)

        if (moduleInstallQueue.length) {
          var next = moduleInstallQueue.splice(0, 1)[0]
          installSKModule(next.name, next.version)
        }

        sendAppStoreChangedEvent()
      }
    )
  }
}

function packageNameIs (name) {
  return x => x.package.name === name
}
<|endoftext|>


<commit_before>var authController = require('../lib/auth');
var User = require('../models/user_model');
var jwt = require('jsonwebtoken');

module.exports = function(app, jwtauth) {
  app.post('/concierge', jwtauth, function(req, res) {
    console.log('this should be the users id: ' + req.user._id);
    User.findOne({'_id': req.user._id}, function(err, user) {
      if (err) {
        console.log('error finding user to add concierge: ' + err);
        return res.status(500).json({message: 'error finding user'});
      }
      if (user === null) {
        console.log('no user found matching that id');
        return res.status(500).json({message: 'no user found matching that id'});
      }
      user.concierge = true;
      user.conciergeAvailable = false;
      user.save(function(err) {
        if (err) return res.status(500).json({message: 'no user found matching that id'});
        console.log('successfully updated user to concierge: ' + user);
        res.status(202).json({concierge: true});
      });
    });
  });
  app.get('/concierge', function(req, res) {
    res.json(req.body);
  });
};
<commit_msg>concierge wip<commit_after>var authController = require('../lib/auth');
var User = require('../models/user_model');
var jwt = require('jsonwebtoken');

module.exports = function(app, jwtauth) {
  app.post('/concierge', jwtauth, function(req, res) {
    console.log('this should be the users id: ' + req.user._id);
    User.findOne({'_id': req.user._id}, function(err, user) {
      if (err) {
        console.log('error finding user to add concierge: ' + err);
        return res.status(500).json({message: 'error finding user'});
      }
      if (user === null) {
        console.log('no user found matching that id');
        return res.status(500).json({message: 'no user found matching that id'});
      }
      user.concierge = true;
      user.conciergeAvailable = false;
      user.save(function(err) {
        if (err) return res.status(500).json({message: 'no user found matching that id'});
        console.log('successfully updated user to concierge: ' + user);
        res.status(202).json({concierge: true});
      });
    });
  });
  app.post('/conciergeAvailable', jwtauth, function(req, res) {
    User.findOne({'_id': req.user._id}, function(err, user) {
      if (err) {
        console.log('error finding Concierge to make available: ' + err);
        return res.status(500).json({message: 'error finding concierge'});
      }
      if (user === null) {
        console.log('no user found matching that id');
        return res.status(500).json({message: 'no user found matching that id'});
      }
      user.conciergeAvailable = true;
      user.save(function(err) {
        if (err) return res.status(500).json({message: 'no user found matching that id'});
        console.log('successfully updated concierge to available: ' + user._id);
        res.status(202).json({conciergeAvailable: true});
      });
    });
  });
  app.get('/concierge', function(req, res) {
    res.json(req.body);
  });
};
<|endoftext|>


<commit_before>var request = require('request');
var fs = require('fs');
global.Commands = require('./commands.js');
fs.readdirSync('./plugins/').forEach(function (file) {
	if (file.substr(-3) === '.js') Object.merge(Commands.commands, require('./plugins/' + file).commands);
});

module.exports = (function () {
	function Parser(serverid) {
		this.serverid = serverid;
	}

	Parser.prototype.parse = function (roomid, data) {
		var server = Servers[this.serverid];
		var parts = data.split('|');
		switch (parts[1]) {
		case 'challstr':
			this.challengekeyid = parts[2];
			this.challenge = parts[3];
			this.login(server.name, server.pass);
			break;
		case 'c:':
			this.parseChat(roomid, parts[3], parts.slice(4).join('|'), '');
			this.logChat(toId(roomid), data);
			updateSeen(parts[3].substr(1, parts[2].length), 'talking', server.id, (~server.privaterooms.indexOf(roomid) ? "a private room" : roomid));
			sendTell(parts[3].substr(1, parts[2].length), server);
			break;
		case 'c':
			this.parseChat(roomid, parts[2], parts.slice(3).join('|'), '');
			this.logChat(toId(roomid), data);
			updateSeen(parts[2].substr(1, parts[2].length), 'talking', server.id, (~server.privaterooms.indexOf(roomid) ? "a private room" : roomid));
			sendTell(parts[2].substr(1, parts[2].length), server);
			break;
		case 'updateuser':
			if (toId(parts[2]) !== toId(server.name)) return;
			server.send('/cmd rooms');
			if (!server.joinedRooms && parts[3] === '1') {
				if (typeof server.rooms === "object") {
					for (var u in server.rooms) server.send('/join ' + server.rooms[u]);
					server.joinedRooms = true;
				}
				for (var i in server.privaterooms) server.send('/join ' + server.privaterooms[i]);
			}
			break;
		case 'pm':
			if (~parts[4].indexOf('/invite') && Commands.hasPermission(parts[2], 'invite')) return server.send('/join ' + parts[4].remove('/invite '));
			this.parseChat(roomid, parts[2], parts.slice(4).join('|'), '/msg ' + parts[2] + ', ');
			sendTell(parts[2].substr(1, parts[2].length), server);
			break;
		case 'join':
		case 'j':
		case 'J':
			updateSeen(parts[2].substr(1, parts[2].length), 'joining', server.id, (~server.privaterooms.indexOf(roomid) ? "a private room" : roomid));
			sendTell(parts[2].substr(1, parts[2].length), server);
			this.logChat(toId(roomid), data);
			break;
		case 'l':
		case 'L':
			updateSeen(parts[2].substr(1, parts[2].length), 'leaving', server.id, (~server.privaterooms.indexOf(roomid) ? "a private room" : roomid));
			this.logChat(toId(roomid), data);
			break;
		case 'raw':
		case 'html':
			this.logChat(toId(roomid), data);
			break;
		case 'queryresponse':
			switch (parts[2]) {
			case 'rooms':
				if (parts[3] === 'null') break;

				var roomData = JSON.parse(parts.slice(3).join('|'));
				server.roomList = {
					'official': [],
					'chat': []
				};
				for (var a in roomData['official']) {
					server.roomList['official'].push(roomData['official'][a].title);
				}
				for (var b in roomData['chat']) {
					server.roomList['chat'].push(roomData['chat'][b].title);
				}
				if (!server.joinedRooms) {
					if (server.rooms === 'all') {
						this.joinAllRooms(true);
						server.joinedRooms = true;
					} else if (server.rooms === 'official') {
						this.joinAllRooms(false);
						server.joinedRooms = true;
					}
				}
				break;
			}
			break;
		default:
			this.logChat(toId(roomid), data);
			break;
		}
	};

	Parser.prototype.joinAllRooms = function (chat) {
		var server = Servers[this.serverid];
		if (!server.roomList) return;
		for (var c in server.roomList.official) {
			server.send('/join ' + server.roomList.official[c]);
		}
		if (chat) {
			for (var d in server.roomList.chat) {
				server.send('/join ' + server.roomList.chat[d]);
			}
		}
	};

	Parser.prototype.parseChat = function (room, user, message, pm) {
		var server = Servers[this.serverid];
		if (!pm) pm = '';
		if (message.charAt(0) === Config.trigger) {
			var command = toId(message.substr(1, (~message.indexOf(' ') ? message.indexOf(' ') : message.length)));
			var target = (~message.indexOf(' ') ? message.substr(message.indexOf(' '), message.length) : '');
			if (Commands.commands[command]) {
				while (typeof Commands.commands[command] !== 'function') {
					command = Commands.commands[command];
				}
				if (typeof Commands.commands[command] === 'function') {
					try {
						Commands.commands[command].call(server, target, room, user, pm);
					} catch (e) {
						server.send(pm + e.stack.substr(0, e.stack.indexOf('\n')), room);
						log(e.stack, server.id, true);
					}
				}
			}
		}
	};

	Parser.prototype.logChat = function (room, data) {
		if (Config.log < 1) return;
		// I'm sure there's a better way to do this instead of a bunch of try-catch
		// but this will work for now
		var date = new Date();
		try {
			fs.statSync('logs/chat');
		} catch (e) {
			fs.mkdirSync('logs/chat', '0755');
		}
		try {
			fs.statSync('logs/chat/' + this.serverid);
		} catch (e) {
			fs.mkdirSync('logs/chat/' + this.serverid, '0755');
		}
		try {
			fs.statSync('logs/chat/' + this.serverid + '/' + room);
		} catch (e) {
			fs.mkdirSync('logs/chat/' + this.serverid + '/' + room, '0755');
		}
		try {
			fs.statSync('logs/chat/' + this.serverid + '/' + room + '/' + date.format('{yyyy}-{MM}'));
		} catch (e) {
			fs.mkdirSync('logs/chat/' + this.serverid + '/' + room + '/' + date.format('{yyyy}-{MM}'), '0755');
		}
		fs.appendFile('logs/chat/' + this.serverid + '/' + room + '/' + date.format('{yyyy}-{MM}') + '/' + date.format('{yyyy}-{MM}-{dd}') + '.txt', data + '\n');
	};

	Parser.prototype.login = function (name, pass) {
		var server = Servers[this.serverid];
		var self = this;
		var options;
		if (pass !== '') {
			options = {
				headers: {
					'content-type': 'application/x-www-form-urlencoded'
				},
				url: 'http://play.pokemonshowdown.com/action.php',
				body: "act=login&name=" + encodeURIComponent(name) + "&pass=" + encodeURIComponent(pass) + "&challengekeyid=" + this.challengekeyid + "&challenge=" + this.challenge
			};
			request.post(options, callback);
		} else {
			options = {
				url: 'http://play.pokemonshowdown.com/action.php?act=getassertion&userid=' + toId(name) + '&challengekeyid=' + this.challengekeyid + '&challenge=' + this.challenge
			};
			request(options, callback);
		}

		function callback(error, response, body) {
			if (body === ';') return log('Failed to log in, name is registered', self.serverid);
			if (body.length < 50) return log('Failed to log in: ' + body, self.serverid);
			if (~body.indexOf('heavy load')) {
				log('Failed to log in - login server is under heavy load. Retrying in one minute.', self.serverid);
				setTimeout(function () {
					self.login(name, pass);
				}, 60 * 1000);
				return;
			}
			if (body.substr(0, 16) === '<!DOCTYPE html>') {
				log('Connection error 522 - retrying in one minute', self.serverid);
				setTimeout(function () {
					self.login(name, pass);
				}, 60 * 1000);
				return;
			}
			try {
				var json = JSON.parse(body.substr(1, body.length));
				if (json.actionsuccess) {
					server.send('/trn ' + name + ',0,' + json['assertion']);
				} else {
					log('Could not log in: ' + JSON.stringify(json), self.serverid);
				}
			} catch (e) {
				server.send('/trn ' + name + ',0,' + body);
			}
		}
	};
	return Parser;
})();
<commit_msg>Fix logging mutes<commit_after>var request = require('request');
var fs = require('fs');
global.Commands = require('./commands.js');
fs.readdirSync('./plugins/').forEach(function (file) {
	if (file.substr(-3) === '.js') Object.merge(Commands.commands, require('./plugins/' + file).commands);
});

module.exports = (function () {
	function Parser(serverid) {
		this.serverid = serverid;
	}

	Parser.prototype.parse = function (roomid, data) {
		var server = Servers[this.serverid];
		if (data.charAt(0) !== '|') data = '||' + data;
		var parts = data.split('|');
		switch (parts[1]) {
		case 'challstr':
			this.challengekeyid = parts[2];
			this.challenge = parts[3];
			this.login(server.name, server.pass);
			break;
		case 'c:':
			this.parseChat(roomid, parts[3], parts.slice(4).join('|'), '');
			this.logChat(toId(roomid), data);
			updateSeen(parts[3].substr(1, parts[2].length), 'talking', server.id, (~server.privaterooms.indexOf(roomid) ? "a private room" : roomid));
			sendTell(parts[3].substr(1, parts[2].length), server);
			break;
		case 'c':
			this.parseChat(roomid, parts[2], parts.slice(3).join('|'), '');
			this.logChat(toId(roomid), data);
			updateSeen(parts[2].substr(1, parts[2].length), 'talking', server.id, (~server.privaterooms.indexOf(roomid) ? "a private room" : roomid));
			sendTell(parts[2].substr(1, parts[2].length), server);
			break;
		case 'updateuser':
			if (toId(parts[2]) !== toId(server.name)) return;
			server.send('/cmd rooms');
			if (!server.joinedRooms && parts[3] === '1') {
				if (typeof server.rooms === "object") {
					for (var u in server.rooms) server.send('/join ' + server.rooms[u]);
					server.joinedRooms = true;
				}
				for (var i in server.privaterooms) server.send('/join ' + server.privaterooms[i]);
			}
			break;
		case 'pm':
			if (~parts[4].indexOf('/invite') && Commands.hasPermission(parts[2], 'invite')) return server.send('/join ' + parts[4].remove('/invite '));
			this.parseChat(roomid, parts[2], parts.slice(4).join('|'), '/msg ' + parts[2] + ', ');
			sendTell(parts[2].substr(1, parts[2].length), server);
			break;
		case 'join':
		case 'j':
		case 'J':
			updateSeen(parts[2].substr(1, parts[2].length), 'joining', server.id, (~server.privaterooms.indexOf(roomid) ? "a private room" : roomid));
			sendTell(parts[2].substr(1, parts[2].length), server);
			this.logChat(toId(roomid), data);
			break;
		case 'l':
		case 'L':
			updateSeen(parts[2].substr(1, parts[2].length), 'leaving', server.id, (~server.privaterooms.indexOf(roomid) ? "a private room" : roomid));
			this.logChat(toId(roomid), data);
			break;
		case 'raw':
		case 'html':
			if (data.substr(0, 50) !== '

') {
				this.logChat(toId(roomid), data);
			}
			break;
		case 'queryresponse':
			switch (parts[2]) {
			case 'rooms':
				if (parts[3] === 'null') break;

				var roomData = JSON.parse(parts.slice(3).join('|'));
				server.roomList = {
					'official': [],
					'chat': []
				};
				for (var a in roomData['official']) {
					server.roomList['official'].push(roomData['official'][a].title);
				}
				for (var b in roomData['chat']) {
					server.roomList['chat'].push(roomData['chat'][b].title);
				}
				if (!server.joinedRooms) {
					if (server.rooms === 'all') {
						this.joinAllRooms(true);
						server.joinedRooms = true;
					} else if (server.rooms === 'official') {
						this.joinAllRooms(false);
						server.joinedRooms = true;
					}
				}
				break;
			}
			break;
		case 'N':
			if (~data.indexOf('\n')) {
				this.logChat(toId(roomid), data.trim());
			}
			break;
		case '':
			this.logChat(toId(roomid), parts.slice(2).join('|'));
			break;
		}
	};

	Parser.prototype.joinAllRooms = function (chat) {
		var server = Servers[this.serverid];
		if (!server.roomList) return;
		for (var c in server.roomList.official) {
			server.send('/join ' + server.roomList.official[c]);
		}
		if (chat) {
			for (var d in server.roomList.chat) {
				server.send('/join ' + server.roomList.chat[d]);
			}
		}
	};

	Parser.prototype.parseChat = function (room, user, message, pm) {
		var server = Servers[this.serverid];
		if (!pm) pm = '';
		if (message.charAt(0) === Config.trigger) {
			var command = toId(message.substr(1, (~message.indexOf(' ') ? message.indexOf(' ') : message.length)));
			var target = (~message.indexOf(' ') ? message.substr(message.indexOf(' '), message.length) : '');
			if (Commands.commands[command]) {
				while (typeof Commands.commands[command] !== 'function') {
					command = Commands.commands[command];
				}
				if (typeof Commands.commands[command] === 'function') {
					try {
						Commands.commands[command].call(server, target, room, user, pm);
					} catch (e) {
						server.send(pm + e.stack.substr(0, e.stack.indexOf('\n')), room);
						log(e.stack, server.id, true);
					}
				}
			}
		}
	};

	Parser.prototype.logChat = function (room, data) {
		if (Config.log < 1) return;
		// I'm sure there's a better way to do this instead of a bunch of try-catch
		// but this will work for now
		var date = new Date();
		try {
			fs.statSync('logs/chat');
		} catch (e) {
			fs.mkdirSync('logs/chat', '0755');
		}
		try {
			fs.statSync('logs/chat/' + this.serverid);
		} catch (e) {
			fs.mkdirSync('logs/chat/' + this.serverid, '0755');
		}
		try {
			fs.statSync('logs/chat/' + this.serverid + '/' + room);
		} catch (e) {
			fs.mkdirSync('logs/chat/' + this.serverid + '/' + room, '0755');
		}
		try {
			fs.statSync('logs/chat/' + this.serverid + '/' + room + '/' + date.format('{yyyy}-{MM}'));
		} catch (e) {
			fs.mkdirSync('logs/chat/' + this.serverid + '/' + room + '/' + date.format('{yyyy}-{MM}'), '0755');
		}
		fs.appendFile('logs/chat/' + this.serverid + '/' + room + '/' + date.format('{yyyy}-{MM}') + '/' + date.format('{yyyy}-{MM}-{dd}') + '.txt', data + '\n');
	};

	Parser.prototype.login = function (name, pass) {
		var server = Servers[this.serverid];
		var self = this;
		var options;
		if (pass !== '') {
			options = {
				headers: {
					'content-type': 'application/x-www-form-urlencoded'
				},
				url: 'http://play.pokemonshowdown.com/action.php',
				body: "act=login&name=" + encodeURIComponent(name) + "&pass=" + encodeURIComponent(pass) + "&challengekeyid=" + this.challengekeyid + "&challenge=" + this.challenge
			};
			request.post(options, callback);
		} else {
			options = {
				url: 'http://play.pokemonshowdown.com/action.php?act=getassertion&userid=' + toId(name) + '&challengekeyid=' + this.challengekeyid + '&challenge=' + this.challenge
			};
			request(options, callback);
		}

		function callback(error, response, body) {
			if (body === ';') return log('Failed to log in, name is registered', self.serverid);
			if (body.length < 50) return log('Failed to log in: ' + body, self.serverid);
			if (~body.indexOf('heavy load')) {
				log('Failed to log in - login server is under heavy load. Retrying in one minute.', self.serverid);
				setTimeout(function () {
					self.login(name, pass);
				}, 60 * 1000);
				return;
			}
			if (body.substr(0, 16) === '<!DOCTYPE html>') {
				log('Connection error 522 - retrying in one minute', self.serverid);
				setTimeout(function () {
					self.login(name, pass);
				}, 60 * 1000);
				return;
			}
			try {
				var json = JSON.parse(body.substr(1, body.length));
				if (json.actionsuccess) {
					server.send('/trn ' + name + ',0,' + json['assertion']);
				} else {
					log('Could not log in: ' + JSON.stringify(json), self.serverid);
				}
			} catch (e) {
				server.send('/trn ' + name + ',0,' + body);
			}
		}
	};
	return Parser;
})();
<|endoftext|>


<commit_before>var Benchmark = require('benchmark');
var assert = require('assert');
var suite = new Benchmark.Suite;

var Parser = require('./../lib/parser');
var ParserOLD = require('./old/parser');

function returnError(error) {
	// throw error; silent for err error perf test
}

function checkReply() {
}

var startBuffer = new Buffer('$100\r\nabcdefghij');
var chunkBuffer = new Buffer('abcdefghijabcdefghijabcdefghij');
var stringBuffer = new Buffer('+testing a simple string\r\n');
var integerBuffer = new Buffer(':1237884\r\n');
var errorBuffer = new Buffer('-Error ohnoesitbroke\r\n');
var arrayBuffer = new Buffer('*1\r\n*1\r\n$1\r\na\r\n');
var endBuffer = new Buffer('\r\n');

var parserOld = new ParserOLD({
	returnReply: checkReply,
	returnError: returnError,
	returnFatalError: returnError,
	name: 'javascript'
});

var parserHiRedis = new Parser({
	returnReply: checkReply,
	returnError: returnError,
	returnFatalError: returnError,
	name: 'hiredis'
});

var parser = new Parser({
	returnReply: checkReply,
	returnError: returnError,
	returnFatalError: returnError,
	name: 'javascript'
});

// BULK STRINGS

suite.add('OLD CODE: multiple chunks in a bulk string', function () {
	parserOld.execute(startBuffer);
	parserOld.execute(chunkBuffer);
	parserOld.execute(chunkBuffer);
	parserOld.execute(chunkBuffer);
	parserOld.execute(endBuffer);
});

suite.add('HIREDIS: multiple chunks in a bulk string', function () {
	parserHiRedis.execute(startBuffer);
	parserHiRedis.execute(chunkBuffer);
	parserHiRedis.execute(chunkBuffer);
	parserHiRedis.execute(chunkBuffer);
	parserHiRedis.execute(endBuffer);
});

suite.add('NEW CODE: multiple chunks in a bulk string', function () {
	parser.execute(startBuffer);
	parser.execute(chunkBuffer);
	parser.execute(chunkBuffer);
	parser.execute(chunkBuffer);
	parser.execute(endBuffer);
});

// STRINGS

suite.add('\nOLD CODE: + simple string', function () {
	parserOld.execute(stringBuffer);
});

suite.add('HIREDIS: + simple string', function () {
	parserHiRedis.execute(stringBuffer);
});

suite.add('NEW CODE: + simple string', function () {
	parser.execute(stringBuffer);
});

// INTEGERS

suite.add('\nOLD CODE: + integer', function () {
	parserOld.execute(integerBuffer);
});

suite.add('HIREDIS: + integer', function () {
	parserHiRedis.execute(integerBuffer);
});

suite.add('NEW CODE: + integer', function () {
	parser.execute(integerBuffer);
});

// ARRAYS

suite.add('\nOLD CODE: * array', function () {
	parserOld.execute(arrayBuffer);
});

suite.add('HIREDIS: * array', function () {
	parserHiRedis.execute(arrayBuffer);
});

suite.add('NEW CODE: * array', function () {
	parser.execute(arrayBuffer);
});

// ERRORS

suite.add('\nOLD CODE: * error', function () {
	parserOld.execute(errorBuffer);
});

suite.add('HIREDIS: * error', function () {
	parserHiRedis.execute(errorBuffer);
});

suite.add('NEW CODE: * error', function () {
	parser.execute(errorBuffer);
});

// add listeners
suite.on('cycle', function (event) {
	console.log(String(event.target));
});

suite.on('complete', function () {
	console.log('\n\nFastest is ' + this.filter('fastest').map('name'));
});

suite.run({delay:2, minSamples: 100 });<commit_msg>Add big data to benchmark<commit_after>var Benchmark = require('benchmark');
var suite = new Benchmark.Suite();

var Parser = require('./../');
var ParserOLD = require('./old/parser');

function returnError (error) {
	error = null;
}

function checkReply () {}

function shuffle (array) {
	var currentIndex = array.length;
	var temporaryValue;
	var randomIndex;

	// While there remain elements to shuffle...
	while (currentIndex !== 0) {
		// Pick a remaining element...
		randomIndex = Math.floor(Math.random() * currentIndex);
		currentIndex -= 1;

		// And swap it with the current element.
		temporaryValue = array[currentIndex];
		array[currentIndex] = array[randomIndex];
		array[randomIndex] = temporaryValue;
	}

	return array;
}

var startBuffer = new Buffer('$100\r\nabcdefghij');
var chunkBuffer = new Buffer('abcdefghijabcdefghijabcdefghij');
var stringBuffer = new Buffer('+testing a simple string\r\n');
var integerBuffer = new Buffer(':1237884\r\n');
var errorBuffer = new Buffer('-Error ohnoesitbroke\r\n');
var arrayBuffer = new Buffer('*1\r\n*1\r\n$1\r\na\r\n');
var endBuffer = new Buffer('\r\n');
var lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, ' +
	'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ' +
	'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ' +
	'ut aliquip ex ea commodo consequat. Duis aute irure dolor in'; // 256 chars
var bigStringArray = (new Array(Math.pow(2, 16) / lorem.length).join(lorem + ' ')).split(' '); // Math.pow(2, 16) chars long
var startBigBuffer = new Buffer('$' + (4 * 1024 * 1024) + '\r\n' + lorem);
var chunks = new Array(64);
for (var i = 0; i < 64; i++) {
	chunks[i] = new Buffer(shuffle(bigStringArray).join(' ') + '.'); // Math.pow(2, 16) chars long
}

var parserOld = new ParserOLD({
	returnReply: checkReply,
	returnError: returnError,
	returnFatalError: returnError,
	name: 'javascript'
});

var parserHiRedis = new Parser({
	returnReply: checkReply,
	returnError: returnError,
	returnFatalError: returnError,
	name: 'hiredis'
});

var parser = new Parser({
	returnReply: checkReply,
	returnError: returnError,
	returnFatalError: returnError,
	name: 'javascript'
});

// BULK STRINGS

suite.add('OLD CODE: multiple chunks in a bulk string', function () {
	parserOld.execute(startBuffer);
	parserOld.execute(chunkBuffer);
	parserOld.execute(chunkBuffer);
	parserOld.execute(chunkBuffer);
	parserOld.execute(endBuffer);
});

suite.add('HIREDIS: multiple chunks in a bulk string', function () {
	parserHiRedis.execute(startBuffer);
	parserHiRedis.execute(chunkBuffer);
	parserHiRedis.execute(chunkBuffer);
	parserHiRedis.execute(chunkBuffer);
	parserHiRedis.execute(endBuffer);
});

suite.add('NEW CODE: multiple chunks in a bulk string', function () {
	parser.execute(startBuffer);
	parser.execute(chunkBuffer);
	parser.execute(chunkBuffer);
	parser.execute(chunkBuffer);
	parser.execute(endBuffer);
});

// BIG BULK STRING

suite.add('\nOLD CODE: 4mb bulk string', function () {
	parserOld.execute(startBigBuffer);
	for (var i = 0; i < 64; i++) {
		parserOld.execute(chunks[i]);
	}
	parserOld.execute(endBuffer);
});

suite.add('HIREDIS: 4mb bulk string', function () {
	parserHiRedis.execute(startBigBuffer);
	for (var i = 0; i < 64; i++) {
		parserHiRedis.execute(chunks[i]);
	}
	parserHiRedis.execute(endBuffer);
});

suite.add('NEW CODE: 4mb bulk string', function () {
	parser.execute(startBigBuffer);
	for (var i = 0; i < 64; i++) {
		parser.execute(chunks[i]);
	}
	parser.execute(endBuffer);
});

// STRINGS

suite.add('\nOLD CODE: + simple string', function () {
	parserOld.execute(stringBuffer);
});

suite.add('HIREDIS: + simple string', function () {
	parserHiRedis.execute(stringBuffer);
});

suite.add('NEW CODE: + simple string', function () {
	parser.execute(stringBuffer);
});

// INTEGERS

suite.add('\nOLD CODE: + integer', function () {
	parserOld.execute(integerBuffer);
});

suite.add('HIREDIS: + integer', function () {
	parserHiRedis.execute(integerBuffer);
});

suite.add('NEW CODE: + integer', function () {
	parser.execute(integerBuffer);
});

// ARRAYS

suite.add('\nOLD CODE: * array', function () {
	parserOld.execute(arrayBuffer);
});

suite.add('HIREDIS: * array', function () {
	parserHiRedis.execute(arrayBuffer);
});

suite.add('NEW CODE: * array', function () {
	parser.execute(arrayBuffer);
});

// ERRORS

suite.add('\nOLD CODE: * error', function () {
	parserOld.execute(errorBuffer);
});

suite.add('HIREDIS: * error', function () {
	parserHiRedis.execute(errorBuffer);
});

suite.add('NEW CODE: * error', function () {
	parser.execute(errorBuffer);
});

// add listeners
suite.on('cycle', function (event) {
	console.log(String(event.target));
});

suite.on('complete', function () {
	console.log('\n\nFastest is ' + this.filter('fastest').map('name'));
});

suite.run({ delay: 1, minSamples: 150 });
<|endoftext|>


<commit_before>//reqs...measureValue
var React = require('react');
var _ = require('underscore');
var connect = require('react-redux').connect;
var utils = require('../../../../utils/componentUtils');
var sampleUtils = require('../../../../utils/sampleUtils');

var AnovaResult = require('./AnovaResult');
var BarChart = require('./BarChart');
var StatsTable = require('./StatsTable');
var HistogramWrapper = require('./HistogramWrapper');

// componet that takes in indvarID + measureID
var mapStateToProps = function(state, ownProps) {
  var samples = utils.getSamplesForMeasure(state, ownProps.measureId, ownProps.indVarId);
  return {
    indVarName : samples.indVarName,
    indVar : state.IndVars.get(ownProps.indVarId).toJS(),
    measure : state.Measures.get(ownProps.measureId).toJS(),
    samples : samples,
  };
};

var ChartWrapper = React.createClass({
  render: function() {
    var samples = sampleUtils.getValues(this.props.samples.samples);
    return (

        <AnovaResult samples={samples} />
        <BarChart samples={this.props.samples} indVar={this.props.indVar} measure={this.props.measure} />
        <StatsTable samples={samples} />
        <HistogramWrapper samples={samples} bins={10} />

    );
  }
});

// export chart
module.exports = connect(mapStateToProps)(ChartWrapper);
<commit_msg>chartwrapper css compliant<commit_after>//reqs...measureValue
var React = require('react');
var _ = require('underscore');
var connect = require('react-redux').connect;
var utils = require('../../../../utils/componentUtils');
var sampleUtils = require('../../../../utils/sampleUtils');

var AnovaResult = require('./AnovaResult');
var BarChart = require('./BarChart');
var StatsTable = require('./StatsTable');
var HistogramWrapper = require('./HistogramWrapper');

// componet that takes in indvarID + measureID
var mapStateToProps = function(state, ownProps) {
  var samples = utils.getSamplesForMeasure(state, ownProps.measureId, ownProps.indVarId);
  return {
    indVarName : samples.indVarName,
    indVar : state.IndVars.get(ownProps.indVarId).toJS(),
    measure : state.Measures.get(ownProps.measureId).toJS(),
    samples : samples,
  };
};

var ChartWrapper = React.createClass({
  render: function() {
    var samples = sampleUtils.getValues(this.props.samples.samples);
    return (

        <AnovaResult samples={samples} />
        <BarChart samples={this.props.samples} indVar={this.props.indVar} measure={this.props.measure} />
        <StatsTable samples={samples} />
        <HistogramWrapper samples={samples} bins={10} />

    );
  }
});

// export chart
module.exports = connect(mapStateToProps)(ChartWrapper);
<|endoftext|>


<commit_before>const chai = require('chai');
const expect = chai.expect;
const mongoose = require('mongoose');
const Message = require('../model/message');

let data = {
    userId: 134256,
    currencyFrom: 'EUR',
    currencyTo: 'GBP',
    amountSell: 1000,
    amountBuy: 747.10,
    rate: 0.7471,
    timePlaced: '24-JAN-15 10:27:44',
    originatingCountry: 'FR'
};

describe('Model', () => {

    before((done) => {
        mongoose.connect('mongodb://127.0.01/market-trade-test-db', {
            useMongoClient: true
        });

        mongoose.connection.on('error', console.error.bind(console, 'connection error:'));

        mongoose.connection.once('open', () => {
            done();
        });
    });

    describe('userId', () => {
        it('should be a number', (done) => {
            const msg = Object.assign({}, data, {
                userId: 'fifty six',
            });

            let message = new Message(msg);

            message.save((err, message) => {
                expect(err).to.be.an('object');

                done();
            });
        });
    });

    describe('currencyFrom', () => {
        it('should be a valid currency code', (done) => {
            const msg = Object.assign({}, data, {
                currencyFrom: 'some string that is not a currency code',
            });

            let message = new Message(msg);

            message.save((err, message) => {
                expect(err).to.be.an('object');
                expect(err.errors).to.have.property('currencyFrom');
                expect(err.errors.currencyFrom.message).to.equal('currencyFrom must be a valid currency code');

                done();
            });
        });
    });

    describe('currencyTo', () => {
        it('should be a valid currency code', (done) => {
            const msg = Object.assign({}, data, {
                currencyTo: 'somestringthatisnotacurrencycode',
            });

            let message = new Message(msg);

            message.save((err, message) => {
                expect(err).to.be.an('object');
                expect(err.errors).to.have.property('currencyTo');
                expect(err.errors.currencyTo.message).to.equal('currencyTo must be a valid currency code');

                done();
            });
        });
    });

    describe('amountSell', () => {
        it('should be a valid number', (done) => {
            const msg = Object.assign({}, data, {
                amountSell: 'twentysix',
            });

            let message = new Message(msg);

            message.save((err, message) => {
                expect(err).to.be.an('object');
                expect(err.errors).to.have.property('amountSell');

                done();
            });
        });
    });

    describe('Valid data', () => {
        it('should save successfully', (done) => {
            let message = new Message(data);

            message.save((err, message) => {
                expect(message).to.be.an('object');

                done();
            });
        });
    });

    after((done) => {
        mongoose.disconnect();

        done();
    });

});<commit_msg>Running consecutive faulty model saves and testing results after<commit_after>const chai = require('chai');
const expect = chai.expect;
const mongoose = require('mongoose');
const Promise = require('bluebird');
const Message = require('../model/message');

const data = {
    userId: 134256,
    currencyFrom: 'EUR',
    currencyTo: 'GBP',
    amountSell: 1000,
    amountBuy: 747.10,
    rate: 0.7471,
    timePlaced: '24-JAN-15 10:27:44',
    originatingCountry: 'FR'
};

describe('Model', () => {

    /**
     * Set up DB connection
     */
    before((done) => {
        mongoose.connect('mongodb://127.0.01/market-trade-test-db', {
            useMongoClient: true
        });

        mongoose.connection.on('error', console.error.bind(console, 'connection error:'));

        mongoose.connection.once('open', () => {
            done();
        });
    });

    describe('userId', () => {
        it('should be a number', (done) => {
            const ids = ['fifty six', null];

            Promise.all(ids.map((userId) => {
                const msg = Object.assign({}, data, { userId });

                return new Message(msg).save().reflect();
            })).each((inspection) => {
                const result = inspection.reason();

                expect(result).to.be.an('object');
                expect(result).to.have.property('errors');

            }).then(done());
        });
    });

    describe('currencyFrom', () => {
        it('should be a valid currency code', (done) => {
            const msg = Object.assign({}, data, {
                currencyFrom: 'some string that is not a currency code',
            });

            new Message(msg).save((err, message) => {
                expect(err).to.be.an('object');
                expect(err.errors).to.have.property('currencyFrom');
                expect(err.errors.currencyFrom.message).to.equal('currencyFrom must be a valid currency code');

                done();
            });
        });
    });

    describe('currencyTo', () => {
        it('should be a valid currency code', (done) => {
            const msg = Object.assign({}, data, {
                currencyTo: 'somestringthatisnotacurrencycode',
            });

            new Message(msg).save((err, message) => {
                expect(err).to.be.an('object');
                expect(err.errors).to.have.property('currencyTo');
                expect(err.errors.currencyTo.message).to.equal('currencyTo must be a valid currency code');

                done();
            });
        });
    });

    describe('amountSell', () => {
        it('should be a valid number', (done) => {
            const msg = Object.assign({}, data, {
                amountSell: 'twentysix',
            });

            new Message(msg).save((err, message) => {
                expect(err).to.be.an('object');
                expect(err.errors).to.have.property('amountSell');

                done();
            });
        });
    });

    describe('Valid data', () => {
        it('should save successfully', (done) => {
            new Message(data).save((err, message) => {
                expect(message).to.be.an('object');

                done();
            });
        });
    });

    /**
     * Close DB connection
     */
    after((done) => {
        mongoose.disconnect();

        done();
    });

});<|endoftext|>