<commit_before>var JSHint = require('jshint').JSHINT;
var CSSLint = require('csslint');
var cssparse = require('css');
var acorn = require('acorn');
var domify = require('domify');
var JscsStringChecker = require('jscs/lib/string-checker.js');
var _ = require('lodash');

var ResponseTypes = {
	LINT : 'lint',
	STYLE : 'style',
	ERROR : 'error',
	FAILURE : 'failure',
	SUCCESS : 'success'
};

var extend = function(a, b){
	var surrogate = function(){};
	surrogate.prototype = a.prototype;
	b.prototype = new surrogate();
};

var Response = function(type, message, errors){
	this.type = type;
	this.message = message || '';
	this.errors = errors;
};

var RinzaiError = function(message, line, char){
	this.message = message;
	this.line = line;
	this.char = char;
};

var Question = function(config, options){
	this.options = options;
	this.test = config.test;
	this.envUrl = config.envUrl;
	this.messages = config.messages || {};
	this.type = config.type;
};

Question.prototype.createEnvironment = function(cb){
	var self = this;
	this.envFrame = document.createElement('iframe');
	this.envFrame.style.position = 'absolute';
	this.envFrame.style.top = '-1000px';
	this.envFrame.style.left = '-1000px';
	document.body.appendChild(this.envFrame);
	var env = this.envFrame.contentWindow;
	if(this.envUrl){
		this.envFrame.src = this.envUrl;
		var onLoad = function(){
			self.envFrame.removeEventListener('load', onLoad);
			cb(env);
		};
		this.envFrame.addEventListener('load', onLoad);
	} else {
		cb(env);
	}
};

Question.prototype.destroyEnvironment = function(){
	if(this.envFrame){
		this.envFrame.parentNode.removeChild(this.envFrame);
	 	delete this.envFrame;
	}
};

Question.prototype.runTest = function(content, parsed, cb){
	var self = this;
	var env = this.createEnvironment(function(env){
		try {
			self.test(content, parsed, env);
		} catch(e) {
			self.destroyEnvironment();
			return cb(e);
		}
		self.destroyEnvironment();
		return cb();
	});
};

var HTMLQuestion = function(){
	Question.apply(this, arguments);
};

extend(Question, HTMLQuestion);

HTMLQuestion.prototype.answer = function(content, cb){
	var self = this;
	var nodes;
	try {
		nodes = domify(content);
	} catch(e) {
		return cb(new Response(
			ResponseTypes.ERROR,
			this.messages[ResponseTypes.ERROR],
			[
				new RinzaiError('HTML Parse Error', null, null)
			]
		));
	}

	this.runTest(content, nodes, function(testErr){
		if(testErr) {
			return cb(new Response(
				ResponseTypes.FAILURE,
				self.messages[ResponseTypes.FAILURE],
				[
					new RinzaiError(testErr.message, null, null)
				]
			));
		}

		return cb(new Response(
			ResponseTypes.SUCCESS,
			self.messages[ResponseTypes.SUCCESS]
		));
	});
};

var JSQuestion = function(){
	Question.apply(this, arguments);
};

extend(Question, JSQuestion);

JSQuestion.prototype.answer = function(content, cb){
	var self = this;

	JSHint(content, this.options.jshint);
	if(JSHint.errors.length){
		return cb(new Response(
			ResponseTypes.LINT,
			this.messages[ResponseTypes.LINT],
			_.map(JSHint.errors, function(err){
				return new RinzaiError(err.reason, err.line);
			})
		));
	}

	var checker = new JscsStringChecker();
	checker.registerDefaultRules();
	checker.configure(this.options.jscs || {});
	var styleErrors = checker.checkString(content);
	if(styleErrors.getErrorList().length){
		return cb(new Response(
			ResponseTypes.STYLE,
			this.messages[ResponseTypes.STYLE],
			_.map(styleErrors.getErrorList(), function(err){
				return new RinzaiError(err.message, err.line, err.column);
			})
		));
	}

	var ast = acorn.parse(content);
	this.runTest(content, ast, function(testErr){
		if(testErr){
			var firstStack = testErr.stack.split('\n')[1];
			if(firstStack && firstStack.indexOf('eval') > -1){
				var position = firstStack.match(/(\d+)\:(\d+)\)$/);
				return cb(new Response(
					ResponseTypes.ERROR,
					self.messages[ResponseTypes.ERROR],
					[
						new RinzaiError(testErr.message, parseInt(position[1], 10), parseInt(position[2], 10))
					]
				));
			} else {
				return cb(new Response(
					ResponseTypes.FAILURE,
					self.messages[ResponseTypes.FAILURE],
					[
						new RinzaiError(testErr.message, null, null)
					]
				));
			}
		}
		return cb(new Response(
			ResponseTypes.SUCCESS,
			self.messages[ResponseTypes.SUCCESS]
		));
	});
};

var CSSQuestion = function(config){
	this.test = config.test;
};

extend(Question, CSSQuestion);

CSSQuestion.prototype.answer = function(content){
	var results = CSSLint(content);
	if(results.messages.length){
		return cb(new Response(
			ResponseTypes.LINT,
			this.messages[ResponseTypes.LINT],
			_.map(results.messages, function(err){
				return new RinzaiError(err.message, err.line, err.col);
			})
		));
	}
	return cb(new Response(
		ResponseTypes.SUCCESS,
		self.messages[ResponseTypes.SUCCESS]
	));
};

var Rinzai = function(config, options){
	this.options = options || {};
	this.questions = [];
	this.questionsById = {};
	_.forEach(config.questions, this.addQuestion, this);
};

Rinzai.prototype.addQuestion = function(q){
	var question;
	switch(q.type){
		case 'html':
			question = new HTMLQuestion(q, this.options);
			break;
		case 'javascript':
			question = new JSQuestion(q, this.options);
			break;
		case 'css':
			question = new CSSQuestion(q, this.options);
			break;
		default:
			throw new Error('Question type is unknown or undefined');
	}
	this.questions.push(question);
	this.questionsById[q.id] = question;
	return question;
};

module.exports = Rinzai;
<commit_msg>Fixed reference to CSSLint verify function<commit_after>var JSHint = require('jshint').JSHINT;
var CSSLint = require('csslint');
var cssparse = require('css');
var acorn = require('acorn');
var domify = require('domify');
var JscsStringChecker = require('jscs/lib/string-checker.js');
var _ = require('lodash');

var ResponseTypes = {
	LINT : 'lint',
	STYLE : 'style',
	ERROR : 'error',
	FAILURE : 'failure',
	SUCCESS : 'success'
};

var extend = function(a, b){
	var surrogate = function(){};
	surrogate.prototype = a.prototype;
	b.prototype = new surrogate();
};

var Response = function(type, message, errors){
	this.type = type;
	this.message = message || '';
	this.errors = errors;
};

var RinzaiError = function(message, line, char){
	this.message = message;
	this.line = line;
	this.char = char;
};

var Question = function(config, options){
	this.options = options;
	this.test = config.test;
	this.envUrl = config.envUrl;
	this.messages = config.messages || {};
	this.type = config.type;
};

Question.prototype.createEnvironment = function(cb){
	var self = this;
	this.envFrame = document.createElement('iframe');
	this.envFrame.style.position = 'absolute';
	this.envFrame.style.top = '-1000px';
	this.envFrame.style.left = '-1000px';
	document.body.appendChild(this.envFrame);
	var env = this.envFrame.contentWindow;
	if(this.envUrl){
		this.envFrame.src = this.envUrl;
		var onLoad = function(){
			self.envFrame.removeEventListener('load', onLoad);
			cb(env);
		};
		this.envFrame.addEventListener('load', onLoad);
	} else {
		cb(env);
	}
};

Question.prototype.destroyEnvironment = function(){
	if(this.envFrame){
		this.envFrame.parentNode.removeChild(this.envFrame);
	 	delete this.envFrame;
	}
};

Question.prototype.runTest = function(content, parsed, cb){
	var self = this;
	var env = this.createEnvironment(function(env){
		try {
			self.test(content, parsed, env);
		} catch(e) {
			self.destroyEnvironment();
			return cb(e);
		}
		self.destroyEnvironment();
		return cb();
	});
};

var HTMLQuestion = function(){
	Question.apply(this, arguments);
};

extend(Question, HTMLQuestion);

HTMLQuestion.prototype.answer = function(content, cb){
	var self = this;
	var nodes;
	try {
		nodes = domify(content);
	} catch(e) {
		return cb(new Response(
			ResponseTypes.ERROR,
			this.messages[ResponseTypes.ERROR],
			[
				new RinzaiError('HTML Parse Error', null, null)
			]
		));
	}

	this.runTest(content, nodes, function(testErr){
		if(testErr) {
			return cb(new Response(
				ResponseTypes.FAILURE,
				self.messages[ResponseTypes.FAILURE],
				[
					new RinzaiError(testErr.message, null, null)
				]
			));
		}

		return cb(new Response(
			ResponseTypes.SUCCESS,
			self.messages[ResponseTypes.SUCCESS]
		));
	});
};

var JSQuestion = function(){
	Question.apply(this, arguments);
};

extend(Question, JSQuestion);

JSQuestion.prototype.answer = function(content, cb){
	var self = this;

	JSHint(content, this.options.jshint);
	if(JSHint.errors.length){
		return cb(new Response(
			ResponseTypes.LINT,
			this.messages[ResponseTypes.LINT],
			_.map(JSHint.errors, function(err){
				return new RinzaiError(err.reason, err.line);
			})
		));
	}

	var checker = new JscsStringChecker();
	checker.registerDefaultRules();
	checker.configure(this.options.jscs || {});
	var styleErrors = checker.checkString(content);
	if(styleErrors.getErrorList().length){
		return cb(new Response(
			ResponseTypes.STYLE,
			this.messages[ResponseTypes.STYLE],
			_.map(styleErrors.getErrorList(), function(err){
				return new RinzaiError(err.message, err.line, err.column);
			})
		));
	}

	var ast = acorn.parse(content);
	this.runTest(content, ast, function(testErr){
		if(testErr){
			var firstStack = testErr.stack.split('\n')[1];
			if(firstStack && firstStack.indexOf('eval') > -1){
				var position = firstStack.match(/(\d+)\:(\d+)\)$/);
				return cb(new Response(
					ResponseTypes.ERROR,
					self.messages[ResponseTypes.ERROR],
					[
						new RinzaiError(testErr.message, parseInt(position[1], 10), parseInt(position[2], 10))
					]
				));
			} else {
				return cb(new Response(
					ResponseTypes.FAILURE,
					self.messages[ResponseTypes.FAILURE],
					[
						new RinzaiError(testErr.message, null, null)
					]
				));
			}
		}
		return cb(new Response(
			ResponseTypes.SUCCESS,
			self.messages[ResponseTypes.SUCCESS]
		));
	});
};

var CSSQuestion = function(config){
	this.test = config.test;
};

extend(Question, CSSQuestion);

CSSQuestion.prototype.answer = function(content){
	var results = CSSLint.verify(content);
	if(results.messages.length){
		return cb(new Response(
			ResponseTypes.LINT,
			this.messages[ResponseTypes.LINT],
			_.map(results.messages, function(err){
				return new RinzaiError(err.message, err.line, err.col);
			})
		));
	}
	return cb(new Response(
		ResponseTypes.SUCCESS,
		self.messages[ResponseTypes.SUCCESS]
	));
};

var Rinzai = function(config, options){
	this.options = options || {};
	this.questions = [];
	this.questionsById = {};
	_.forEach(config.questions, this.addQuestion, this);
};

Rinzai.prototype.addQuestion = function(q){
	var question;
	switch(q.type){
		case 'html':
			question = new HTMLQuestion(q, this.options);
			break;
		case 'javascript':
			question = new JSQuestion(q, this.options);
			break;
		case 'css':
			question = new CSSQuestion(q, this.options);
			break;
		default:
			throw new Error('Question type is unknown or undefined');
	}
	this.questions.push(question);
	this.questionsById[q.id] = question;
	return question;
};

module.exports = Rinzai;
<|endoftext|>


<commit_before>Router.map(function () {

	this.route('index', {path: '/', template: 'index', layoutTemplate: 'indexLayout'});

	/////////////////////////////////////////////////
	///////////////////// Anime /////////////////////
	/////////////////////////////////////////////////

	// Defined for compatibilty with pages
	this.route('animeExplore', {path: '/anime/explore'});

	this.route('animeAdd', {path: '/anime/add'});

	this.route('anime', {path: '/anime/:slug'});

	/////////////////////////////////////////////////
	////////////////// Character ////////////////////
	/////////////////////////////////////////////////

	this.route('characters');
	this.route('character', {path: 'characters/:_id/:fullNameSlug'});
	this.route('charactersAdd', {path: 'characters/add'});

	/////////////////////////////////////////////////
	//////////////////// People /////////////////////
	/////////////////////////////////////////////////

	this.route('people', {layoutTemplate: 'defaultLayout'});
	this.route('person', {path: '/people/:_id/:fullNameSlug'});
	this.route('peopleAdd', {path: 'people/add'});

	/////////////////////////////////////////////////
	//////////////////// Studios ////////////////////
	/////////////////////////////////////////////////
	this.route('studiosAdd', {path: 'studios/add'});

	/////////////////////////////////////////////////
	/////////////////// Castings ////////////////////
	/////////////////////////////////////////////////
	this.route('castingsAdd', {path: 'castings/add'});

	/////////////////////////////////////////////////
	///////////////// staffMembers //////////////////
	/////////////////////////////////////////////////
	this.route('staffMembersAdd', {path: 'staff-members/add'});

	/////////////////////////////////////////////////
	/////////////////// Reviews /////////////////////
	/////////////////////////////////////////////////

	this.route('review', {path: '/anime/:slug/reviews/:_id'});

	/////////////////////////////////////////////////
	///////////////////// User //////////////////////
	/////////////////////////////////////////////////

	this.route('user', {path: '/users/:username', layoutTemplate: 'userProfileLayout'});
	this.route('userLibrary', {path: '/users/:username/library', layoutTemplate: 'userProfileLayout'});
	this.route('userFollowers', {path: '/users/:username/followers', layoutTemplate: 'userProfileLayout'});
	this.route('userFollowing', {path: '/users/:username/following', layoutTemplate: 'userProfileLayout'});

	/////////////////////////////////////////////////
	///////////////////// User //////////////////////
	/////////////////////////////////////////////////

	this.route('accountPersonalDetails', {path: '/account/personal-details', layoutTemplate: 'accountLayout'});
	this.route('accountSecurity', {path: '/account/security', layoutTemplate: 'accountLayout'});
	this.route('accountPreferences', {path: '/account/preferences', layoutTemplate: 'accountLayout'});

	/////////////////////////////////////////////////
	//////////////////// General ////////////////////
	/////////////////////////////////////////////////

	// Search

	this.route('search', {path: 'search'});

	// Related routes

	this.route('signIn', {path: 'sign-in'});
	this.route('signOut', {path: 'sign-out'});
	this.route('signUp', {path: 'sign-up'});

	// 404 not found route

	this.route('fourOhFour', {path: "*"});

});

////////////////
// BeforeHooks
////////////////
// I use an object that contains all before hooks
var routerBeforeHooks = {

	isLoggedIn: function(pause) {
		if (!(Meteor.loggingIn() || Meteor.user())) {
			this.render('signIn');
			pause();
		}
	},

	isAdmin: function(pause) {
		if (!(Meteor.loggingIn() || Meteor.user().isAdmin())) {
			this.render('permissionDenied');
			pause();
		}
	},

	landingPage: function(pause) {
		if (!(Meteor.loggingIn() || Meteor.user())) {
			this.render('landing');
			pause();
		}
	},

	// We want to ensure that when a new page loads
	// we have it scrolled all the way to the top
	scrollUp: function() {
		$('body, html').scrollTop(0);
	},
	animateContentIn: function() {
		$('.container.main-content').addClass("animated fadeIn fateInRight");
		$('footer').removeClass("hide");
	}
}

// Run these global routes first
Router.onBeforeAction('loading');
Router.onBeforeAction(routerBeforeHooks.isLoggedIn);

// Render the landing page if the user isn't logged in on index
Router.onBeforeAction(routerBeforeHooks.landingPage, {only: ['index']});

// These routes need admin permissions
Router.onBeforeAction(routerBeforeHooks.isAdmin, {only: ['animeAdd', 'charactersAdd', 'peopleAdd', 'studiosAdd', 'staffMembersAdd', 'castingsAdd']});

// Router.onBeforeAction('dataNotFound');

// Global hooks that every page needs
// Router.onBeforeAction(routerBeforeHooks.loadingIndicator, routerBeforeHooks.isLoggedIn, routerBeforeHooks.scrollUp);

Router.configure({
	layoutTemplate: 'defaultLayout',
	notFoundTemplate: 'fourOhFour',
	loadingTemplate: 'loading',
	onBeforeAction: function(pause) {
		// routerBeforeHooks.scrollUp();
		// routerBeforeHooks.isLoggedIn(pause);

		// routerBeforeHooks.loadingIndicator();
		// routerBeforeHooks.animateContentIn();
	}
});

// // Before hooks for specific routes
// // Must be equal to the route names of the Iron Router route map
// Router.before(IR_BeforeHooks.isLoggedIn, {only: ['userAreaA', 'userAreaB']});<commit_msg>Added logged in hooks, and redirect signin sign up pages<commit_after>Router.map(function () {

	this.route('index', {path: '/', template: 'index', layoutTemplate: 'indexLayout'});

	/////////////////////////////////////////////////
	///////////////////// Anime /////////////////////
	/////////////////////////////////////////////////

	// Defined for compatibilty with pages
	this.route('animeExplore', {path: '/anime/explore'});

	this.route('animeAdd', {path: '/anime/add'});

	this.route('anime', {path: '/anime/:slug'});

	/////////////////////////////////////////////////
	////////////////// Character ////////////////////
	/////////////////////////////////////////////////

	this.route('characters');
	this.route('character', {path: 'characters/:_id/:fullNameSlug'});
	this.route('charactersAdd', {path: 'characters/add'});

	/////////////////////////////////////////////////
	//////////////////// People /////////////////////
	/////////////////////////////////////////////////

	this.route('people', {layoutTemplate: 'defaultLayout'});
	this.route('person', {path: '/people/:_id/:fullNameSlug'});
	this.route('peopleAdd', {path: 'people/add'});

	/////////////////////////////////////////////////
	//////////////////// Studios ////////////////////
	/////////////////////////////////////////////////
	this.route('studiosAdd', {path: 'studios/add'});

	/////////////////////////////////////////////////
	/////////////////// Castings ////////////////////
	/////////////////////////////////////////////////
	this.route('castingsAdd', {path: 'castings/add'});

	/////////////////////////////////////////////////
	///////////////// staffMembers //////////////////
	/////////////////////////////////////////////////
	this.route('staffMembersAdd', {path: 'staff-members/add'});

	/////////////////////////////////////////////////
	/////////////////// Reviews /////////////////////
	/////////////////////////////////////////////////

	this.route('review', {path: '/anime/:slug/reviews/:_id'});

	/////////////////////////////////////////////////
	///////////////////// User //////////////////////
	/////////////////////////////////////////////////

	this.route('user', {path: '/users/:username', layoutTemplate: 'userProfileLayout'});
	this.route('userLibrary', {path: '/users/:username/library', layoutTemplate: 'userProfileLayout'});
	this.route('userFollowers', {path: '/users/:username/followers', layoutTemplate: 'userProfileLayout'});
	this.route('userFollowing', {path: '/users/:username/following', layoutTemplate: 'userProfileLayout'});

	/////////////////////////////////////////////////
	///////////////////// User //////////////////////
	/////////////////////////////////////////////////

	this.route('accountPersonalDetails', {path: '/account/personal-details', layoutTemplate: 'accountLayout'});
	this.route('accountSecurity', {path: '/account/security', layoutTemplate: 'accountLayout'});
	this.route('accountPreferences', {path: '/account/preferences', layoutTemplate: 'accountLayout'});

	/////////////////////////////////////////////////
	//////////////////// General ////////////////////
	/////////////////////////////////////////////////

	// Search

	this.route('search', {path: 'search'});

	// Related routes

	this.route('signIn', {path: 'sign-in'});
	this.route('signOut', {path: 'sign-out'});
	this.route('signUp', {path: 'sign-up'});

	// 404 not found route

	this.route('fourOhFour', {path: "*"});

});

////////////////
// BeforeHooks
////////////////
// I use an object that contains all before hooks
var routerBeforeHooks = {

	isLoggedIn: function(pause) {
		if (!(Meteor.loggingIn() || Meteor.user())) {
			this.render('signIn');
			pause();
		}
	},

	isAlreadyLoggedIn: function(pause) {
		if (Meteor.loggingIn() || Meteor.user()) {
			Router.go('index');
		}
	},

	isAdmin: function(pause) {
		if (!(Meteor.loggingIn() || Meteor.user().isAdmin())) {
			this.render('permissionDenied');
			pause();
		}
	},

	landingPage: function(pause) {
		if (!(Meteor.loggingIn() || Meteor.user())) {
			this.render('landing');
			pause();
		}
	},

	// We want to ensure that when a new page loads
	// we have it scrolled all the way to the top
	scrollUp: function() {
		$('body, html').scrollTop(0);
	},
	animateContentIn: function() {
		$('.container.main-content').addClass("animated fadeIn fateInRight");
		$('footer').removeClass("hide");
	}
}

// Run these global routes first
Router.onBeforeAction('loading');
Router.onBeforeAction(routerBeforeHooks.isLoggedIn, {except: ['signIn', 'signUp']});
Router.onBeforeAction(routerBeforeHooks.isAlreadyLoggedIn, {only: ['signIn', 'signUp']});

// Render the landing page if the user isn't logged in on index
Router.onBeforeAction(routerBeforeHooks.landingPage, {only: ['index']});

// These routes need admin permissions
Router.onBeforeAction(routerBeforeHooks.isAdmin, {only: ['animeAdd', 'charactersAdd', 'peopleAdd', 'studiosAdd', 'staffMembersAdd', 'castingsAdd']});

// Router.onBeforeAction('dataNotFound');

// Global hooks that every page needs
// Router.onBeforeAction(routerBeforeHooks.loadingIndicator, routerBeforeHooks.isLoggedIn, routerBeforeHooks.scrollUp);

Router.configure({
	layoutTemplate: 'defaultLayout',
	notFoundTemplate: 'fourOhFour',
	loadingTemplate: 'loading',
	onBeforeAction: function(pause) {
		// routerBeforeHooks.scrollUp();
		// routerBeforeHooks.isLoggedIn(pause);

		// routerBeforeHooks.loadingIndicator();
		// routerBeforeHooks.animateContentIn();
	}
});

// // Before hooks for specific routes
// // Must be equal to the route names of the Iron Router route map
// Router.before(IR_BeforeHooks.isLoggedIn, {only: ['userAreaA', 'userAreaB']});<|endoftext|>


<commit_before>///////////////////////////////////////
//get requests
///////////////////////////////////////

app.get('/HV', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/HV.jade');
});

app.get('/GRIFFIN', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('detectors/GRIFFIN.jade');
});

app.get('/DAQ', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/DAQ.jade');
});

app.get('/PPG', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/PPG.jade');
});

app.get('/Clocks', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Clock.jade');
});

app.get('/Filter', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Filter.jade');
});

///////////////////////////////////////
//post routes
///////////////////////////////////////

app.post('/postHV', function(req, res){

	spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Variables/Demand["+req.body.chIndex+"] " + req.body.demandVoltage]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Up Speed["+req.body.chIndex+"]' " + req.body.voltageUp]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Down Speed["+req.body.chIndex+"]' " + req.body.voltageDown]);

	if(req.body.powerSwitch == 'off')
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 0"]);
	else
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 1"]);

	return res.redirect('/HV?crate=0&channel='+req.body.chName);
});

app.post('/registerCycle', function(req, res){
	var cycle = (req.body.cycleString) ? JSON.parse(req.body.cycleString) : null,
		i,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}

	//register a new cycle
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}

	spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "mkdir /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}

	return res.redirect('/PPG');
});

app.post('/registerFilter', function(req, res){
	var filter = (req.body.filterString) ? JSON.parse(req.body.filterString) : null,
		i, j,
		steps = [],
		durations = [];

/*
	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}
*/
	//register a new filter
	/*
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}
	*/

	/*
	spawn('odbedit', ['-c', "rm /Filter/Filters/" + req.body.filterName]);
	spawn('odbedit', ['-c', "mkdir /Filter/Filters/" + req.body.filterName]);

	for(i=0; i<filter.length; i++){
		spawn('odbedit', ['-c', "create string /Filter/Filters/" + req.body.filterName + "/orCondition"+i+"[" + filter[i].length + "]" ]);
		for(j=0; j<filter[i].length; j++){
			spawn('odbedit', ['-c', "set /Filter/Filters/" + req.body.filterName + "/orCondition"+i + '['+j+'] ' + filter[i][j] ]);
		}
	}
	*/

	exec('odbedit -c rm /Filter/Filters/' + req.body.filterName, function(){});
	exec('odbedit -c mkdir /Filter/Filters/' + req.body.filterName, function(){});

	for(i=0; i<filter.length; i++){
		exec('odbedit -c create string /Filter/Filters/' + req.body.filterName + '/orCondition'+i+'[' + filter[i].length + "]", function(){});
		for(j=0; j<filter[i].length; j++){
			exec('odbedit -c set /Filter/Filters/' + req.body.filterName + '/orCondition'+i + '['+j+'] ' + filter[i][j], function(){} );
		}
	}

	/*
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}
*/
	return res.redirect('/Filter');

});

app.post('/updateClock', function(req, res){
	var ClockEnB = 0,
		powerOn,
		stepdown = parseInt(req.body.freqStepdown,10);

	//channel on / off
	for(i=0; i<6; i++){
		powerOn = req.body['eSATAtoggle' + i] == 1
		ClockEnB = ClockEnB | ((powerOn) ? (0xF << 4*i) : 0);
	}
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[0] " + ClockEnB]);

	//freq. stepdown
	if(stepdown && req.body.isMaster=='1'){
		for(i=0; i<8; i++){
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (11+4*i) + "] " + stepdown]);
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (12+4*i) + "] " + stepdown]);
		}
	}

	return res.redirect('/Clocks');
});

app.post('/toggleClock', function(req, res){
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[1] " + req.body['radio'+req.body.clockIndex] ]);

	return res.redirect('/Clocks');
})

<commit_msg>fighting with weird ODB writing problems - try exec?<commit_after>///////////////////////////////////////
//get requests
///////////////////////////////////////

app.get('/HV', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/HV.jade');
});

app.get('/GRIFFIN', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('detectors/GRIFFIN.jade');
});

app.get('/DAQ', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/DAQ.jade');
});

app.get('/PPG', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/PPG.jade');
});

app.get('/Clocks', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Clock.jade');
});

app.get('/Filter', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Filter.jade');
});

///////////////////////////////////////
//post routes
///////////////////////////////////////

app.post('/postHV', function(req, res){

	spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Variables/Demand["+req.body.chIndex+"] " + req.body.demandVoltage]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Up Speed["+req.body.chIndex+"]' " + req.body.voltageUp]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Down Speed["+req.body.chIndex+"]' " + req.body.voltageDown]);

	if(req.body.powerSwitch == 'off')
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 0"]);
	else
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 1"]);

	return res.redirect('/HV?crate=0&channel='+req.body.chName);
});

app.post('/registerCycle', function(req, res){
	var cycle = (req.body.cycleString) ? JSON.parse(req.body.cycleString) : null,
		i,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}

	//register a new cycle
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}

	spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "mkdir /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}

	return res.redirect('/PPG');
});

app.post('/registerFilter', function(req, res){
	var filter = (req.body.filterString) ? JSON.parse(req.body.filterString) : null,
		i, j,
		steps = [],
		durations = [];

/*
	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}
*/
	//register a new filter
	/*
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}
	*/

	/*
	spawn('odbedit', ['-c', "rm /Filter/Filters/" + req.body.filterName]);
	spawn('odbedit', ['-c', "mkdir /Filter/Filters/" + req.body.filterName]);

	for(i=0; i<filter.length; i++){
		spawn('odbedit', ['-c', "create string /Filter/Filters/" + req.body.filterName + "/orCondition"+i+"[" + filter[i].length + "]" ]);
		for(j=0; j<filter[i].length; j++){
			spawn('odbedit', ['-c', "set /Filter/Filters/" + req.body.filterName + "/orCondition"+i + '['+j+'] ' + filter[i][j] ]);
		}
	}
	*/

	exec('odbedit -c rm /Filter/Filters/' + req.body.filterName, function(){});
	exec('odbedit -c mkdir /Filter/Filters/' + req.body.filterName, function(){});
	exec('ls', function(error, stdout, stderr){
		console.log([error, stdout, stderr]);
	})
	for(i=0; i<filter.length; i++){
		exec('odbedit -c create string /Filter/Filters/' + req.body.filterName + '/orCondition'+i+'[' + filter[i].length + "]", function(){});
		for(j=0; j<filter[i].length; j++){
			exec('odbedit -c set /Filter/Filters/' + req.body.filterName + '/orCondition'+i + '['+j+'] ' + filter[i][j], function(){} );
		}
	}

	/*
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}
*/
	return res.redirect('/Filter');

});

app.post('/updateClock', function(req, res){
	var ClockEnB = 0,
		powerOn,
		stepdown = parseInt(req.body.freqStepdown,10);

	//channel on / off
	for(i=0; i<6; i++){
		powerOn = req.body['eSATAtoggle' + i] == 1
		ClockEnB = ClockEnB | ((powerOn) ? (0xF << 4*i) : 0);
	}
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[0] " + ClockEnB]);

	//freq. stepdown
	if(stepdown && req.body.isMaster=='1'){
		for(i=0; i<8; i++){
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (11+4*i) + "] " + stepdown]);
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (12+4*i) + "] " + stepdown]);
		}
	}

	return res.redirect('/Clocks');
});

app.post('/toggleClock', function(req, res){
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[1] " + req.body['radio'+req.body.clockIndex] ]);

	return res.redirect('/Clocks');
})

<|endoftext|>


<commit_before>'use strict';

var models    = require('./models'),
    passport  = require('passport');

module.exports = function(app) {

  var isAuthenticated = function (req, res, next) {
    if (req.isAuthenticated())
      return next();
    res.redirect('/login');
  }

  // home page
  app.get('/', function(req, res) {
    models.Match.table(models, req.params.season).then(function(table) {
      res.render('standings', {
        title: 'Standings',
        league: table
      });
    });;
  })

  // login
  app.route('/login')
    .get(function(req, res) {
      res.render('login', {
        title: 'Login'
      })
    })
    .post(passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/login',
      })
    );

  app.get('/logout', isAuthenticated, function(req, res) {
    req.logout();
    req.flash('message', 'User Logged Off');
    res.redirect('/');
  })

  // static pages
  app.get('/rules', function(req, res) {
    res.render('rules', {
      title: 'Rules'
    })
  })

  app.get('/format', function(req, res) {
    res.render('format', {
      title: 'League Format'
    })
  })

  // get the standings
  // optionally add a year to get that year's table
  app.get('/standings/:season?', function(req, res) {
    models.Match.table(models, req.params.season).then(function(table) {
      res.render('standings', {
        title: 'Standings',
        league: table,
        season: req.params.season || 2016
      })
    });
  })

  // get a team's result
  app.get('/teams/:id/:season?', function(req, res) {
    var team = models.Team.findById(req.params.id);
    var matches = models.Match.findAll({
      where: { $and: [{ season: req.params.season || app.locals.season }, { $or: [{ teama_id: req.params.id }, { teamb_id: req.params.id }] }] },
      raw: true,
      attributes: [
        'id',
        'score',
        'teama_id',
        'teamb_id',
        'round',
        [models.sequelize.fn('date_format', models.sequelize.col('date'), app.locals.date_format), 'date'],
      ],
      include: [{
        model: models.Team,
        as: 'TeamA',
        attributes: ['id', 'name']
      }, {
        model: models.Team,
        as: 'TeamB',
        attributes: ['id', 'name']
      }]
    });
    models.sequelize.Promise.join(
      team,
      matches,
      function(team, matches) {
        team.logo = team.name.replace(/\s|\'/g, '').toLowerCase() + '.png';
        for (var x = 0; x < matches.length; x++) {
          var scores = [], result = null;
          if (matches[x].teama_id == req.params.id) {
            matches[x].home = true;
            matches[x].logo = matches[x]['TeamB.name'].replace(/\s|\'/g, '').toLowerCase() + '.png';
          } else {
            matches[x].home = false;
            matches[x].logo = matches[x]['TeamA.name'].replace(/\s|\'/g, '').toLowerCase() + '.png';
          }

          if (matches[x].score) {
            scores = matches[x].score.split('-').map(function(e) { return e * 1; });
            if (matches[x].home) {
              matches[x].cls = (scores[0] > scores[1]) ? 'win' : 'lose';
            } else {
              matches[x].cls = (scores[0] < scores[1]) ? 'win' : 'lose';
              // if selected team is 'away' then reverse the order of the score
              matches[x].score = matches[x].score.split('-').reverse().join('-');
            }
          } else {
            matches[x].score = '-';
          }
        }
        res.render('teams', {
          title: team.name,
          team: team,
          matches: matches
        })
      })
  })

  app.get('/weeks/:id?/:season?', function(req, res) {
    models.Match.fixtures(models, req.params.id, req.params.season).then(function(data) {
      res.render('weeks', {
        title: (data.length == 1) ? 'Week ' + data[0].round : 'Fixtures',
        weeks: data
      })
    })
  })

  // handle the ajax POST of a result
  app.post('/matches/:id', function(req, res) {

    if (req.user) {
      models.Match.update({
        score: req.body.score
      }, {
        where: [{ id: req.params.id }, { season: 2016 }]
      }).then(function(rows) {
        res.send(rows == 1);
      })
    } else {
      res.sendStatus(403);
    }
  })

}<commit_msg>add current week's games to home page<commit_after>'use strict';

var models    = require('./models'),
    moment    = require('moment'),
    passport  = require('passport');

module.exports = function(app) {

  var isAuthenticated = function (req, res, next) {
    if (req.isAuthenticated())
      return next();
    res.redirect('/login');
  }

  // home page
  app.get('/', function(req, res) {
    /*models.Match.table(models, req.params.season).then(function(table) {
      res.render('standings', {
        title: 'Standings',
        league: table
      });
    });*/
    // get current day, then work out the Wednesday, then week id
    let start = moment('2016 04 11', 'YYYY MM DD'),
        now = moment('');
    var week = (Math.floor(now.diff(start, 'days') / 7) + 1) || 1;
    console.log(week);
    models.Match.fixtures(models, week, 2016).then(function(data) {
      res.render('weeks', {
        title: 'This Week\'s Games',
        weeks: data
      })
    })
  })

  // login
  app.route('/login')
    .get(function(req, res) {
      res.render('login', {
        title: 'Login'
      })
    })
    .post(passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/login',
      })
    );

  app.get('/logout', isAuthenticated, function(req, res) {
    req.logout();
    req.flash('message', 'User Logged Off');
    res.redirect('/');
  })

  // static pages
  app.get('/rules', function(req, res) {
    res.render('rules', {
      title: 'Rules'
    })
  })

  app.get('/format', function(req, res) {
    res.render('format', {
      title: 'League Format'
    })
  })

  // get the standings
  // optionally add a year to get that year's table
  app.get('/standings/:season?', function(req, res) {
    models.Match.table(models, req.params.season).then(function(table) {
      res.render('standings', {
        title: 'Standings',
        league: table,
        season: req.params.season || 2016
      })
    });
  })

  // get a team's result
  app.get('/teams/:id/:season?', function(req, res) {
    var team = models.Team.findById(req.params.id);
    var matches = models.Match.findAll({
      where: { $and: [{ season: req.params.season || app.locals.season }, { $or: [{ teama_id: req.params.id }, { teamb_id: req.params.id }] }] },
      raw: true,
      attributes: [
        'id',
        'score',
        'teama_id',
        'teamb_id',
        'round',
        [models.sequelize.fn('date_format', models.sequelize.col('date'), app.locals.date_format), 'date'],
      ],
      include: [{
        model: models.Team,
        as: 'TeamA',
        attributes: ['id', 'name']
      }, {
        model: models.Team,
        as: 'TeamB',
        attributes: ['id', 'name']
      }]
    });
    models.sequelize.Promise.join(
      team,
      matches,
      function(team, matches) {
        team.logo = team.name.replace(/\s|\'/g, '').toLowerCase() + '.png';
        for (var x = 0; x < matches.length; x++) {
          var scores = [], result = null;
          if (matches[x].teama_id == req.params.id) {
            matches[x].home = true;
            matches[x].logo = matches[x]['TeamB.name'].replace(/\s|\'/g, '').toLowerCase() + '.png';
          } else {
            matches[x].home = false;
            matches[x].logo = matches[x]['TeamA.name'].replace(/\s|\'/g, '').toLowerCase() + '.png';
          }

          if (matches[x].score) {
            scores = matches[x].score.split('-').map(function(e) { return e * 1; });
            if (matches[x].home) {
              matches[x].cls = (scores[0] > scores[1]) ? 'win' : 'lose';
            } else {
              matches[x].cls = (scores[0] < scores[1]) ? 'win' : 'lose';
              // if selected team is 'away' then reverse the order of the score
              matches[x].score = matches[x].score.split('-').reverse().join('-');
            }
          } else {
            matches[x].score = '-';
          }
        }
        res.render('teams', {
          title: team.name,
          team: team,
          matches: matches
        })
      })
  })

  app.get('/weeks/:id?/:season?', function(req, res) {
    models.Match.fixtures(models, req.params.id, req.params.season).then(function(data) {
      res.render('weeks', {
        weeks: data
      })
    })
  })

  // handle the ajax POST of a result
  app.post('/matches/:id', function(req, res) {

    if (req.user) {
      models.Match.update({
        score: req.body.score
      }, {
        where: [{ id: req.params.id }, { season: 2016 }]
      }).then(function(rows) {
        res.send(rows == 1);
      })
    } else {
      res.sendStatus(403);
    }
  })

}<|endoftext|>


<commit_before>///////////////////////////////////////
//get requests
///////////////////////////////////////

app.get('/HV', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/HV.jade');
});

app.get('/GRIFFIN', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('detectors/GRIFFIN.jade');
});

app.get('/DAQ', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/DAQ.jade');
});

app.get('/PPG', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/PPG.jade');
});

app.get('/Clocks', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Clock.jade');
});

app.get('/Filter', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Filter.jade');
});

///////////////////////////////////////
//post routes
///////////////////////////////////////

app.post('/postHV', function(req, res){

	spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Variables/Demand["+req.body.chIndex+"] " + req.body.demandVoltage]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Up Speed["+req.body.chIndex+"]' " + req.body.voltageUp]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Down Speed["+req.body.chIndex+"]' " + req.body.voltageDown]);

	if(req.body.powerSwitch == 'off')
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 0"]);
	else
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 1"]);

	return res.redirect('/HV?crate=0&channel='+req.body.chName);
});

app.post('/registerCycle', function(req, res){
	var cycle = (req.body.cycleString) ? JSON.parse(req.body.cycleString) : null,
		i,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}

	//register a new cycle
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}

	spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "mkdir /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}

	return res.redirect('/PPG');
});

app.post('/registerFilter', function(req, res){
	var filter = (req.body.filterString) ? JSON.parse(req.body.filterString) : null,
		i, j,
		steps = [],
		durations = [];

/*
	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}
*/
	//register a new filter
	/*
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}
	*/
	spawn('odbedit', ['-c', "rm /Filter/Filters/" + req.body.filterName]);
	spawn('odbedit', ['-c', "mkdir /Filter/Filters/" + req.body.filterName]);

console.log(filter)

	for(i=0; i<filter.length; i++){
		spawn('odbedit', ['-c', "create string /Filter/Filters/" + req.body.filterName + "/orCondition"+i+"[" + filter[i].length + "]" ]);
		for(j=0; j<filter[i].length; j++){
			console.log(filter[i][j]);

			spawn('odbedit', ['-c', "set /Filter/Filters/" + req.body.filterName + "/orCondition"+i + '['+j+'] ' + filter[i][j] ]);
		}
	}

	/*
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}
*/
	return res.redirect('/Filter');

});

app.post('/updateClock', function(req, res){
	var ClockEnB = 0,
		powerOn,
		stepdown = parseInt(req.body.freqStepdown,10);

	//channel on / off
	for(i=0; i<6; i++){
		powerOn = req.body['eSATAtoggle' + i] == 1
		ClockEnB = ClockEnB | ((powerOn) ? (0xF << 4*i) : 0);
	}
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[0] " + ClockEnB]);

	//freq. stepdown
	if(stepdown && req.body.isMaster=='1'){
		for(i=0; i<8; i++){
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (11+4*i) + "] " + stepdown]);
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (12+4*i) + "] " + stepdown]);
		}
	}

	return res.redirect('/Clocks');
});

app.post('/toggleClock', function(req, res){
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[1] " + req.body['radio'+req.body.clockIndex] ]);

	return res.redirect('/Clocks');
})

<commit_msg>working out filter commit route<commit_after>///////////////////////////////////////
//get requests
///////////////////////////////////////

app.get('/HV', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/HV.jade');
});

app.get('/GRIFFIN', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('detectors/GRIFFIN.jade');
});

app.get('/DAQ', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/DAQ.jade');
});

app.get('/PPG', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/PPG.jade');
});

app.get('/Clocks', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Clock.jade');
});

app.get('/Filter', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Filter.jade');
});

///////////////////////////////////////
//post routes
///////////////////////////////////////

app.post('/postHV', function(req, res){

	spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Variables/Demand["+req.body.chIndex+"] " + req.body.demandVoltage]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Up Speed["+req.body.chIndex+"]' " + req.body.voltageUp]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Down Speed["+req.body.chIndex+"]' " + req.body.voltageDown]);

	if(req.body.powerSwitch == 'off')
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 0"]);
	else
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 1"]);

	return res.redirect('/HV?crate=0&channel='+req.body.chName);
});

app.post('/registerCycle', function(req, res){
	var cycle = (req.body.cycleString) ? JSON.parse(req.body.cycleString) : null,
		i,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}

	//register a new cycle
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}

	spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "mkdir /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}

	return res.redirect('/PPG');
});

app.post('/registerFilter', function(req, res){
	var filter = (req.body.filterString) ? JSON.parse(req.body.filterString) : null,
		i, j,
		steps = [],
		durations = [];

/*
	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}
*/
	//register a new filter
	/*
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}
	*/
	spawn('odbedit', ['-c', "rm /Filter/Filters/" + req.body.filterName]);
	spawn('odbedit', ['-c', "mkdir /Filter/Filters/" + req.body.filterName]);

console.log(filter)

	for(i=0; i<filter.length; i++){
		spawn('odbedit', ['-c', "create string /Filter/Filters/" + req.body.filterName + "/orCondition"+i+"[" + filter[i].length + "]" ]);
		for(j=0; j<filter[i].length; j++){
			console.log(filter[i][j]);

			spawn('odbedit', ['-c', "set /Filter/Filters/" + req.body.filterName + "/orCondition"+i + '['+j+'] ' + JSON.stringify(filter[i][j]) ]);
		}
	}

	/*
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}
*/
	return res.redirect('/Filter');

});

app.post('/updateClock', function(req, res){
	var ClockEnB = 0,
		powerOn,
		stepdown = parseInt(req.body.freqStepdown,10);

	//channel on / off
	for(i=0; i<6; i++){
		powerOn = req.body['eSATAtoggle' + i] == 1
		ClockEnB = ClockEnB | ((powerOn) ? (0xF << 4*i) : 0);
	}
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[0] " + ClockEnB]);

	//freq. stepdown
	if(stepdown && req.body.isMaster=='1'){
		for(i=0; i<8; i++){
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (11+4*i) + "] " + stepdown]);
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (12+4*i) + "] " + stepdown]);
		}
	}

	return res.redirect('/Clocks');
});

app.post('/toggleClock', function(req, res){
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[1] " + req.body['radio'+req.body.clockIndex] ]);

	return res.redirect('/Clocks');
})

<|endoftext|>


<commit_before>var Item = require('./models/item'),
    Order = require('./models/order'),
    Account = require('./models/account'),
    passport = require('passport'),
    mkdirp = require('mkdirp'),
    async = require('async'),
    fs = require('fs'),
    path = require('path'),
    validator = require('./validator'),
    _ = require('underscore'),
    Promise = require('promise');

var titles = {
    'register': 'Mix Dat Up | Register',
    'login': 'Mix Dat Up | Login',
    'menu': 'Mix Dat Up | Menu',
    'editItem': 'Mix Dat Up | Edit Item'
};

function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.redirect('/account/login');
    }
};

function randomNumber() {
    'use strict';
    return Math.floor(Math.random() * 90000) + 10000;
}
module.exports = function(app) {
    'use strict';
    app.post('/account/login',
        passport.authenticate('local', {
            successRedirect: '/',
            failureRedirect: '/account/login'
        }));
    app.get('/account/login', function(req, res) {
        res.render('login', {
            'title': titles.login
        });
    });
    app.get('/account/register', function(req, res) {
        res.render('register', {
            'title': titles.register
        });
    });
    app.post('/account/register', function(req, res) {
        if (req.body.username && req.body.password) {
            var p = new Promise(function(resolve, reject) {
                Account.findByUser(req.body.username, function(err, result) {
                    if (err) {
                        reject(err);
                    } else if (result.length === 0) {
                        resolve(false); //doesn't exist
                    } else {
                        resolve(true);
                    }
                });

            });
            p.then(function success(data) {
                if (data === false) {
                    Account.register(new Account({
                        username: req.body.username
                    }), req.body.password, function(err) {
                        if (err) {
                            res.render('register', {
                                'err': err,
                                'title': titles.register
                            });
                        } else {
                            res.render('register', {
                                'message': 'Registered!',
                                'title': titles.register
                            });
                        }
                    });
                } else {
                    res.render('register', {
                        'err': 'Account already exists',
                        'title': titles.register
                    });
                }
            }, function error(e) {
                res.render('register', {
                    'err': e,
                    'title': titles.register
                });
            });
        } else {
            res.render('register', {
                'err': 'No username or password',
                'title': titles.register
            });
        }

    });

    app.get('/home', function(req, res) {
        res.cookie('table_number', randomNumber());
        res.render('customer/home');
    });

    app.get('/menu/restaurant', function(req, res) {
        var user = req.user || '';
        Item.findByUser(user, function(err, result) {
            if (err) {
                res.render('customer/menu', {
                    err: err
                });
            } else {
                if (req.user.role === 'owner') {
                    res.render('customer/menu', {
                        items: result,
                        owner: true
                    });
                } else {
                    res.render('customer/menu', {
                        items: result,
                        customer: true
                    });
                }
            }
        });
    });

    app.get('/menu', ensureAuthenticated, function(req, res) {
        Item.findAll(function(err, result) {
            if (err) {
                res.render('customer/menu', {
                    err: err
                });
            } else {
                if (req.user.role === 'owner') {
                    res.render('customer/menu', {
                        items: result,
                        owner: true
                    });
                } else {
                    res.render('customer/menu', {
                        items: result,
                        customer: true
                    });
                }
            }
        });
    });

    app.get('/item/view/:id', ensureAuthenticated, function(req, res) {
        var p = new Promise(function(resolve, reject) {
            Item.increaseView(req.params.id, function(err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
        p.then(function success(data) {
            Item.findById(req.params.id, function(err, result) {
                if (err) {
                    res.render('customer/viewItem', {
                        message: err
                    });
                } else {
                    res.render('customer/viewItem', {
                        item: result
                    });
                }
            });
        }, function error(e) {
            res.render('customer/viewItem', {
                message: err
            });
        });
    });
    app.get('/item/picture/:id', ensureAuthenticated, function(req, res) {
        var itemPath = path.join(__dirname, 'public', 'assets', req.params.id);
        fs.readdir(itemPath, function(err, items) {
            if (items && items.length > 0) {
                var item = path.join(itemPath, items[0]);
                res.sendfile(item);
            } else {
                res.send(500);
            }
        });
    });
    app.get('/item/edit/:id', ensureAuthenticated, function(req, res) {
        Item.findById(req.params.id, function(err, result) {
            if (err) {
                res.render('restaurant/editItem', {
                    message: err
                });
            } else {
                res.render('restaurant/editItem', {
                    item: result
                });
            }
        });
    });
    app.get('/item/delete/:id', ensureAuthenticated, function(req, res) {
        Item.update({
            _id: req.params.id
        }, {
            'isDeleted': true
        }, function(err, result) {
            if (err) {
                res.send(500);
            } else {
                res.send(200);
            }
        });
    });
    app.post('/item/edit/:id', ensureAuthenticated, function(req, res) {
        var conditions = req.body;
        conditions.lastModifiedBy = req.user;
        conditions.lastModifiedDate = new Date();
        var p = new Promise(function(resolve, reject) {
            Item.update({
                _id: req.params.id
            }, conditions, function(err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
        p.then(function success(result) {
            fs.readFile(req.files.file.path, function(err, data) {
                var folder = path.join('assets', result._id, req.files.file.originalFilename),
                    pathNew = path.join(__dirname, 'public', folder);
                fs.writeFile(pathNew, data, function(error) {
                    if (error) {
                        res.render('restaurant/editItem', {
                            message: error
                        });
                    } else {
                        res.render('restaurant/editItem', {
                            item: result
                        });
                    }
                });
            });
        }, function error(e) {
            res.render('restaurant/editItem', {
                message: e
            });
        });
    });

    app.get('/item/edit', ensureAuthenticated, function(req, res) {
        Item.findAll(function(err, result) {
            if (err) {
                res.render('restaurant/editItem', {
                    message: err
                });
            } else {
                res.render('restaurant/editItem', {
                    items: result
                });
            }
        });
    });

    app.get('/item/add', ensureAuthenticated, function(req, res) {
        res.render('restaurant/addItem');
    });
    /**
     * These 2 functions need update on the view render path
     **/
    app.post('/item/add', ensureAuthenticated, function(req, res) {
        var conditions = req.body;
        if (req.files.filezilla) {
            conditions.pictures = true;
        }
        conditions.owner = req.user;
        conditions.lastModifiedBy = req.user;
        conditions.lastModifiedDate = new Date();
        var p = new Promise(function(resolve, reject) {
            Item.create(conditions, function(err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
        p.then(function success(result) {
                if (req.files.filezilla) {
                    fs.readFile(req.files.filezilla.path, function(err, data) {
                        var folder = '/assets/' + result._id,
                            pathOld = path.join(__dirname, 'public', folder),
                            pathNew = pathOld + '/' + req.files.filezilla.originalname;
                        mkdirp(pathOld, function(err) {
                            if (err) {
                                res.render('restaurant/addItem', {
                                    message: error
                                });
                            } else {
                                fs.writeFile(pathNew, data, function(error) {
                                    if (error) {
                                        res.render('restaurant/addItem', {
                                            message: error
                                        });
                                    } else {
                                        res.render('restaurant/addItem', {
                                            item: result
                                        });
                                    }
                                });
                            }

                        });

                    });
                } else {
                    res.render('restaurant/addItem', {
                        item: result,
                        msg: 'Successfully added this item'
                    });
                }

            },
            function error(e) {
                res.render('restaurant/addItem', {
                    message: e
                });
            });
    });

    app.get('/item/id/:req.params.id', ensureAuthenticated, function(req, res) {
        Item.findById(req.params.id, function(err, result) {
            if (err) {
                res.render('customer/item', {
                    err: err
                });
            } else {
                res.render('customer/item', {
                    item: result
                });
            }
        });
    });

    app.get('/order/bill', ensureAuthenticated, function(req, res) {
        var tableNumber = req.cookies.table_number || 0,
            total = 0;
        Order.findByTable(tableNumber, function(err, result) {
            if (err) {
                res.render('customer/bill', {
                    err: err
                });
            } else {
                //results
                var items = result[0] || {
                    items: ''
                }
                async.forEach(items.items, function(el, callback) {
                    if (el.id) {
                        Item.findById(el.id, function(error, itemz) {
                            if (err) {
                                callback();
                            } else {
                                total = total + itemz.price;
                                callback();
                            }
                        });
                    } else {
                        callback();
                    }

                }, function() {
                    res.render('customer/bill', {
                        item: result,
                        total: total
                    });
                });
            }
        });
    });
    app.post('/order/add', ensureAuthenticated, function(req, res) {
        var tableNumber = req.cookies.table_number,
            conditions = {};
        conditions['items'] = req.cookies.cart;
        if (tableNumber === undefined) {
            tableNumber = randomNumber();
            res.cookie('table_number', tableNumber);
        }

        if (!conditions || conditions.length === 0) {
            res.send(500, 'Empty, no data sent');
        }
        conditions.lastModifiedBy = req.user;
        conditions.lastModifiedDate = new Date();
        conditions.owner = req.user;
        conditions.tableNumber = tableNumber;

        var p = new Promise(function(resolve, reject) {
            Order.findByTable(tableNumber, function(err, result) {
                if (err) {
                    reject(err);
                } else if (result.length === 0 || !result) {
                    resolve(false);
                } else {
                    resolve(result);
                }
            });
        });
        p.then(function success(data) {
            if (data === false) {
                if (conditions.items) {
                    conditions.items = JSON.parse(conditions.items);
                }
                Order.create(conditions, function(err, result) {
                    if (err) {
                        res.send(500, e);
                    } else {
                        res.send(200, result);
                    }
                });
            } else {
                var params = {};
                var host = [];
                host.push.apply(host, JSON.parse(conditions.items));
                if (data[0].items) {
                    host.push.apply(host, data[0].items);
                }
                conditions.items = host;
                params.tableNumber = tableNumber;
                params.statusCode = 1; //ORDERSTATUS_SENT, export later
                Order.update(params, conditions, function(err, result) {
                    if (err) {
                        res.send(500, e);
                    } else {
                        res.send(200, result);
                    }
                });
            }
        }, function error(e) {
            res.render('restaurant/order', {
                err: e
            });
        });

    });
    app.post('/customer/randomizer', ensureAuthenticated, function(req, res) {
        var likes = [],
            dislikes = [];
        if (req.body.like && !(req.body.like instanceof Array)) {
            likes.push(req.body.like);
        } else if (req.body.like instanceof Array) {
            likes = req.body.like;
        }
        if (req.body.dislikes && !(req.body.dislikes instanceof Array)) {
            dislikes.push(req.body.dislikes);
        } else if (req.body.dislikes instanceof Array) {
            dislikes = req.body.dislikes;
        }
        if (likes.length > 0) {
            Item.randomize(likes, dislikes, function(err, result) {
                if (err) {
                    res.render('randomize', {
                        err: err
                    });
                } else {
                    res.render('randomize', {
                        result: result
                    });
                }
            });
        } else {
            Item.randomize(likes, dislikes, function(err, result) {
                if (err) {
                    res.render('randomize', {
                        err: err
                    });
                } else {
                    res.render('randomize', {
                        result: result
                    });
                }
            });
        }
    });
    app.get('/order/stats', ensureAuthenticated, function(req, res) {
        Item.findAll(function(err, collection) {
            if (err) {
                res.render('restaurant/data', {
                    err: err
                });
            } else {
                res.render('restaurant/data', {
                    items: collection
                });
            }
        });
    });
    app.get('/customer/randomizer', ensureAuthenticated, function(req, res) {
        res.render('randomize');
    });

    app.get('/contact', function(req, res) {
        res.render('contact');
    });

    app.get('/order/all', ensureAuthenticated, function(req, res) {
        Order.findAll(function(err, result) {
            if (err) {
                res.render('restaurant/allOrders', {
                    message: err
                });
            } else {
                res.render('restaurant/allOrders', {
                    orders: result
                });
            }
        });
    });

    app.get('/500', function(req, res) {
        res.render('500', {
            error: 'you know better'
        });
    });
    app.get('/', function(req, res) {
        res.sendfile('app/index.html');
    });
    app.get('/order/pending', ensureAuthenticated, function(req, res) {
        Order.find({
            'statusCode': 1
        }, null, {}, function(err, collection) {
            if (err) {
                res.render('restaurant/pendingOrders', {
                    err: err
                });
            } else {
                res.render('restaurant/pendingOrders', {
                    orders: collection
                });
            }
        });
    });
    app.get('/order/id/:id', ensureAuthenticated, function(req, res) {
        Order.findById(req.params.id, function(err, result) {
            if (err) {
                res.render('restaurant/order', {
                    message: err
                });
            } else {
                res.render('restaurant/order', {
                    order: result
                });
            }
        });
    });
    app.post('/order/edit/:id', ensureAuthenticated, function(req, res) {
        var tableNumber = req.cookies.table_number,
            conditions = req.body;
        //conditions.lastModifiedBy = req.user;
        conditions.lastModifiedDate = new Date();
        if (tableNumber === undefined) {
            tableNumber = randomNumber();
            res.cookie('table_number', tableNumber);
        }
        Order.findById(req.params.id, function(err, result) {
            if (err) {
                res.send(500, err);
            } else {
                if (!result || result.length === 0) {
                    conditions.owner = req.user;
                    Order.create(conditions, function(err1, result1) {
                        if (err1) {
                            res.send(500, err1);
                        } else {
                            res.send(200, result1);
                        }
                    });
                } else {
                    Order.update({
                        '_id': req.params.id
                    }, conditions, function(err2, result2) {
                        if (err2) {
                            res.send(500, err2);
                        } else {
                            res.send(200, result2);
                        }
                    });
                }
            }
        });
    });

};<commit_msg>home view render<commit_after>var Item = require('./models/item'),
    Order = require('./models/order'),
    Account = require('./models/account'),
    passport = require('passport'),
    mkdirp = require('mkdirp'),
    async = require('async'),
    fs = require('fs'),
    path = require('path'),
    validator = require('./validator'),
    _ = require('underscore'),
    Promise = require('promise');

var titles = {
    'register': 'Mix Dat Up | Register',
    'login': 'Mix Dat Up | Login',
    'menu': 'Mix Dat Up | Menu',
    'editItem': 'Mix Dat Up | Edit Item'
};

function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.redirect('/account/login');
    }
};

function randomNumber() {
    'use strict';
    return Math.floor(Math.random() * 90000) + 10000;
}
module.exports = function(app) {
    'use strict';
    app.post('/account/login',
        passport.authenticate('local', {
            successRedirect: '/',
            failureRedirect: '/account/login'
        }));
    app.get('/account/login', function(req, res) {
        res.render('login', {
            'title': titles.login
        });
    });
    app.get('/account/register', function(req, res) {
        res.render('register', {
            'title': titles.register
        });
    });
    app.post('/account/register', function(req, res) {
        if (req.body.username && req.body.password) {
            var p = new Promise(function(resolve, reject) {
                Account.findByUser(req.body.username, function(err, result) {
                    if (err) {
                        reject(err);
                    } else if (result.length === 0) {
                        resolve(false); //doesn't exist
                    } else {
                        resolve(true);
                    }
                });

            });
            p.then(function success(data) {
                if (data === false) {
                    Account.register(new Account({
                        username: req.body.username
                    }), req.body.password, function(err) {
                        if (err) {
                            res.render('register', {
                                'err': err,
                                'title': titles.register
                            });
                        } else {
                            res.render('register', {
                                'message': 'Registered!',
                                'title': titles.register
                            });
                        }
                    });
                } else {
                    res.render('register', {
                        'err': 'Account already exists',
                        'title': titles.register
                    });
                }
            }, function error(e) {
                res.render('register', {
                    'err': e,
                    'title': titles.register
                });
            });
        } else {
            res.render('register', {
                'err': 'No username or password',
                'title': titles.register
            });
        }

    });

    app.get('/home', function(req, res) {
        res.cookie('table_number', randomNumber());
        if (req.user.role === 'owner') {
            res.render('customer/home', {
                owner : true
            });
        } else {
            res.render('customer/home', {
                customer : true
            });
        }
    });

    app.get('/menu/restaurant', function(req, res) {
        var user = req.user || '';
        Item.findByUser(user, function(err, result) {
            if (err) {
                res.render('customer/menu', {
                    err: err
                });
            } else {
                if (req.user.role === 'owner') {
                    res.render('customer/menu', {
                        items: result,
                        owner: true
                    });
                } else {
                    res.render('customer/menu', {
                        items: result,
                        customer: true
                    });
                }
            }
        });
    });

    app.get('/menu', ensureAuthenticated, function(req, res) {
        Item.findAll(function(err, result) {
            if (err) {
                res.render('customer/menu', {
                    err: err
                });
            } else {
                if (req.user.role === 'owner') {
                    res.render('customer/menu', {
                        items: result,
                        owner: true
                    });
                } else {
                    res.render('customer/menu', {
                        items: result,
                        customer: true
                    });
                }
            }
        });
    });

    app.get('/item/view/:id', ensureAuthenticated, function(req, res) {
        var p = new Promise(function(resolve, reject) {
            Item.increaseView(req.params.id, function(err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
        p.then(function success(data) {
            Item.findById(req.params.id, function(err, result) {
                if (err) {
                    res.render('customer/viewItem', {
                        message: err
                    });
                } else {
                    res.render('customer/viewItem', {
                        item: result
                    });
                }
            });
        }, function error(e) {
            res.render('customer/viewItem', {
                message: err
            });
        });
    });
    app.get('/item/picture/:id', ensureAuthenticated, function(req, res) {
        var itemPath = path.join(__dirname, 'public', 'assets', req.params.id);
        fs.readdir(itemPath, function(err, items) {
            if (items && items.length > 0) {
                var item = path.join(itemPath, items[0]);
                res.sendfile(item);
            } else {
                res.send(500);
            }
        });
    });
    app.get('/item/edit/:id', ensureAuthenticated, function(req, res) {
        Item.findById(req.params.id, function(err, result) {
            if (err) {
                res.render('restaurant/editItem', {
                    message: err
                });
            } else {
                res.render('restaurant/editItem', {
                    item: result
                });
            }
        });
    });
    app.get('/item/delete/:id', ensureAuthenticated, function(req, res) {
        Item.update({
            _id: req.params.id
        }, {
            'isDeleted': true
        }, function(err, result) {
            if (err) {
                res.send(500);
            } else {
                res.send(200);
            }
        });
    });
    app.post('/item/edit/:id', ensureAuthenticated, function(req, res) {
        var conditions = req.body;
        conditions.lastModifiedBy = req.user;
        conditions.lastModifiedDate = new Date();
        var p = new Promise(function(resolve, reject) {
            Item.update({
                _id: req.params.id
            }, conditions, function(err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
        p.then(function success(result) {
            fs.readFile(req.files.file.path, function(err, data) {
                var folder = path.join('assets', result._id, req.files.file.originalFilename),
                    pathNew = path.join(__dirname, 'public', folder);
                fs.writeFile(pathNew, data, function(error) {
                    if (error) {
                        res.render('restaurant/editItem', {
                            message: error
                        });
                    } else {
                        res.render('restaurant/editItem', {
                            item: result
                        });
                    }
                });
            });
        }, function error(e) {
            res.render('restaurant/editItem', {
                message: e
            });
        });
    });

    app.get('/item/edit', ensureAuthenticated, function(req, res) {
        Item.findAll(function(err, result) {
            if (err) {
                res.render('restaurant/editItem', {
                    message: err
                });
            } else {
                res.render('restaurant/editItem', {
                    items: result
                });
            }
        });
    });

    app.get('/item/add', ensureAuthenticated, function(req, res) {
        res.render('restaurant/addItem');
    });
    /**
     * These 2 functions need update on the view render path
     **/
    app.post('/item/add', ensureAuthenticated, function(req, res) {
        var conditions = req.body;
        if (req.files.filezilla) {
            conditions.pictures = true;
        }
        conditions.owner = req.user;
        conditions.lastModifiedBy = req.user;
        conditions.lastModifiedDate = new Date();
        var p = new Promise(function(resolve, reject) {
            Item.create(conditions, function(err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
        p.then(function success(result) {
                if (req.files.filezilla) {
                    fs.readFile(req.files.filezilla.path, function(err, data) {
                        var folder = '/assets/' + result._id,
                            pathOld = path.join(__dirname, 'public', folder),
                            pathNew = pathOld + '/' + req.files.filezilla.originalname;
                        mkdirp(pathOld, function(err) {
                            if (err) {
                                res.render('restaurant/addItem', {
                                    message: error
                                });
                            } else {
                                fs.writeFile(pathNew, data, function(error) {
                                    if (error) {
                                        res.render('restaurant/addItem', {
                                            message: error
                                        });
                                    } else {
                                        res.render('restaurant/addItem', {
                                            item: result
                                        });
                                    }
                                });
                            }

                        });

                    });
                } else {
                    res.render('restaurant/addItem', {
                        item: result,
                        msg: 'Successfully added this item'
                    });
                }

            },
            function error(e) {
                res.render('restaurant/addItem', {
                    message: e
                });
            });
    });

    app.get('/item/id/:req.params.id', ensureAuthenticated, function(req, res) {
        Item.findById(req.params.id, function(err, result) {
            if (err) {
                res.render('customer/item', {
                    err: err
                });
            } else {
                res.render('customer/item', {
                    item: result
                });
            }
        });
    });

    app.get('/order/bill', ensureAuthenticated, function(req, res) {
        var tableNumber = req.cookies.table_number || 0,
            total = 0;
        Order.findByTable(tableNumber, function(err, result) {
            if (err) {
                res.render('customer/bill', {
                    err: err
                });
            } else {
                //results
                var items = result[0] || {
                    items: ''
                }
                async.forEach(items.items, function(el, callback) {
                    if (el.id) {
                        Item.findById(el.id, function(error, itemz) {
                            if (err) {
                                callback();
                            } else {
                                total = total + itemz.price;
                                callback();
                            }
                        });
                    } else {
                        callback();
                    }

                }, function() {
                    res.render('customer/bill', {
                        item: result,
                        total: total
                    });
                });
            }
        });
    });
    app.post('/order/add', ensureAuthenticated, function(req, res) {
        var tableNumber = req.cookies.table_number,
            conditions = {};
        conditions['items'] = req.cookies.cart;
        if (tableNumber === undefined) {
            tableNumber = randomNumber();
            res.cookie('table_number', tableNumber);
        }

        if (!conditions || conditions.length === 0) {
            res.send(500, 'Empty, no data sent');
        }
        conditions.lastModifiedBy = req.user;
        conditions.lastModifiedDate = new Date();
        conditions.owner = req.user;
        conditions.tableNumber = tableNumber;

        var p = new Promise(function(resolve, reject) {
            Order.findByTable(tableNumber, function(err, result) {
                if (err) {
                    reject(err);
                } else if (result.length === 0 || !result) {
                    resolve(false);
                } else {
                    resolve(result);
                }
            });
        });
        p.then(function success(data) {
            if (data === false) {
                if (conditions.items) {
                    conditions.items = JSON.parse(conditions.items);
                }
                Order.create(conditions, function(err, result) {
                    if (err) {
                        res.send(500, e);
                    } else {
                        res.send(200, result);
                    }
                });
            } else {
                var params = {};
                var host = [];
                host.push.apply(host, JSON.parse(conditions.items));
                if (data[0].items) {
                    host.push.apply(host, data[0].items);
                }
                conditions.items = host;
                params.tableNumber = tableNumber;
                params.statusCode = 1; //ORDERSTATUS_SENT, export later
                Order.update(params, conditions, function(err, result) {
                    if (err) {
                        res.send(500, e);
                    } else {
                        res.send(200, result);
                    }
                });
            }
        }, function error(e) {
            res.render('restaurant/order', {
                err: e
            });
        });

    });
    app.post('/customer/randomizer', ensureAuthenticated, function(req, res) {
        var likes = [],
            dislikes = [];
        if (req.body.like && !(req.body.like instanceof Array)) {
            likes.push(req.body.like);
        } else if (req.body.like instanceof Array) {
            likes = req.body.like;
        }
        if (req.body.dislikes && !(req.body.dislikes instanceof Array)) {
            dislikes.push(req.body.dislikes);
        } else if (req.body.dislikes instanceof Array) {
            dislikes = req.body.dislikes;
        }
        if (likes.length > 0) {
            Item.randomize(likes, dislikes, function(err, result) {
                if (err) {
                    res.render('randomize', {
                        err: err
                    });
                } else {
                    res.render('randomize', {
                        result: result
                    });
                }
            });
        } else {
            Item.randomize(likes, dislikes, function(err, result) {
                if (err) {
                    res.render('randomize', {
                        err: err
                    });
                } else {
                    res.render('randomize', {
                        result: result
                    });
                }
            });
        }
    });
    app.get('/order/stats', ensureAuthenticated, function(req, res) {
        Item.findAll(function(err, collection) {
            if (err) {
                res.render('restaurant/data', {
                    err: err
                });
            } else {
                res.render('restaurant/data', {
                    items: collection
                });
            }
        });
    });
    app.get('/customer/randomizer', ensureAuthenticated, function(req, res) {
        res.render('randomize');
    });

    app.get('/contact', function(req, res) {
        res.render('contact');
    });

    app.get('/order/all', ensureAuthenticated, function(req, res) {
        Order.findAll(function(err, result) {
            if (err) {
                res.render('restaurant/allOrders', {
                    message: err
                });
            } else {
                res.render('restaurant/allOrders', {
                    orders: result
                });
            }
        });
    });

    app.get('/500', function(req, res) {
        res.render('500', {
            error: 'you know better'
        });
    });
    app.get('/', function(req, res) {
        res.sendfile('app/index.html');
    });
    app.get('/order/pending', ensureAuthenticated, function(req, res) {
        Order.find({
            'statusCode': 1
        }, null, {}, function(err, collection) {
            if (err) {
                res.render('restaurant/pendingOrders', {
                    err: err
                });
            } else {
                res.render('restaurant/pendingOrders', {
                    orders: collection
                });
            }
        });
    });
    app.get('/order/id/:id', ensureAuthenticated, function(req, res) {
        Order.findById(req.params.id, function(err, result) {
            if (err) {
                res.render('restaurant/order', {
                    message: err
                });
            } else {
                res.render('restaurant/order', {
                    order: result
                });
            }
        });
    });
    app.post('/order/edit/:id', ensureAuthenticated, function(req, res) {
        var tableNumber = req.cookies.table_number,
            conditions = req.body;
        //conditions.lastModifiedBy = req.user;
        conditions.lastModifiedDate = new Date();
        if (tableNumber === undefined) {
            tableNumber = randomNumber();
            res.cookie('table_number', tableNumber);
        }
        Order.findById(req.params.id, function(err, result) {
            if (err) {
                res.send(500, err);
            } else {
                if (!result || result.length === 0) {
                    conditions.owner = req.user;
                    Order.create(conditions, function(err1, result1) {
                        if (err1) {
                            res.send(500, err1);
                        } else {
                            res.send(200, result1);
                        }
                    });
                } else {
                    Order.update({
                        '_id': req.params.id
                    }, conditions, function(err2, result2) {
                        if (err2) {
                            res.send(500, err2);
                        } else {
                            res.send(200, result2);
                        }
                    });
                }
            }
        });
    });

};<|endoftext|>