<commit_before>import Parser, { linkParser } from '../parser';
import { setAttr, addClass, removeClass } from '../../dom';
import { each, isString, isArray, isObject, diff, warn } from '../../util';

/**
 * 处理 styleObject, 批量更新元素 style
 * @param   {Element}  element
 * @param   {String}   styleObject
 */
function updateStyle (element, styleObject) {
	var style = element.style;

	if (!isObject(styleObject)) {
		return warn('v-bind for style must be a type of Object', styleObject);
	}

	each(styleObject, function (value, property) {
		if (style[property] !== value) {
			style[property] = value;
		}
	});
}

/**
 * 更新元素的 className
 * @param   {Element}  element
 * @param   {Mix}      classValue
 * @param   {Boolean}  remove
 */
function updateClass (element, classValue, remove) {
	var handler = remove ? removeClass : addClass;

	if (isString(classValue)) {
		handler(element, classValue);
	} else if (isArray(classValue)) {
		each(classValue, function (cls) {
			handler(element, cls);
		});
	} else if (isObject(classValue)) {
		each(classValue, function (add, cls) {
			if (remove || !add) {
				removeClass(element, cls);
			} else {
				addClass(element, cls);
			}
		});
	}
}

/**
 * v-bind 指令解析模块
 */
export function VBind () {
	Parser.apply(this, arguments);
}

var vbind = linkParser(VBind);

/**
 * 解析 v-bind 指令
 */
vbind.parse = function () {
	this.desc.deep = true;
	this.bind();
}

/**
 * 视图更新
 * @param   {Mix}  newValue
 * @param   {Mix}  oldValue
 */
vbind.update = function (newValue, oldValue) {
	var type = this.desc.args;
	if (type) {
		this.single(type, newValue, oldValue);
	} else {
		this.multi(newValue, oldValue);
	}
}

/**
 * 解析单个 attribute
 * @param   {String}  type
 * @param   {Mix}     newValue
 * @param   {Mix}     oldValue
 */
vbind.single = function (type, newValue, oldValue) {
	switch (type) {
		case 'class':
			this.handleClass(newValue, oldValue);
			break;
		case 'style':
			this.handleStyle(newValue, oldValue);
			break;
		default:
			this.handleAttr(type, newValue, oldValue);
	}
}

/**
 * 解析 attribute, class, style 组合
 * @param   {Object}  newJson
 * @param   {Object}  oldJson
 */
vbind.multi = function (newJson, oldJson) {
	if (oldJson) {
		let { after, before } = diff(newJson, oldJson);
		this.batch(after, before);
	}

	this.batch(newJson);
}

/**
 * 绑定属性批处理
 * @param   {Object}  newObj
 * @param   {Object}  oldObj
 */
vbind.batch = function (newObj, oldObj) {
	each(newObj, function (value, key) {
		this.single(key, value, oldObj && oldObj[key]);
	}, this);
}

/**
 * 更新处理 className
 * @param   {Mix}  newClass
 * @param   {Mix}  oldClass
 */
vbind.handleClass = function (newClass, oldClass) {
	var el = this.el;

	// 数据更新
	if (oldClass) {
		let { after, before } = diff(newClass, oldClass);
		updateClass(el, before, true);
		updateClass(el, after);
	} else {
		updateClass(el, newClass);
	}
}

/**
 * 更新处理 style
 * @param   {Mix}  newStyle
 * @param   {Mix}  oldStyle
 */
vbind.handleStyle = function (newStyle, oldStyle) {
	var el = this.el;

	// 数据更新
	if (oldStyle) {
		// 移除旧样式(设为 null)
		each(oldStyle, function (v, key) {
			oldStyle[key] = null;
		});

		updateStyle(el, oldStyle);
	}

	updateStyle(el, newStyle);
}

/**
 * 更新处理 attribute
 * @param   {String}   attr
 * @param   {String}   newValue
 * @param   {String}   oldValue
 */
vbind.handleAttr = function (attr, newValue, oldValue) {
	setAttr(this.el, attr, newValue);
}<commit_msg>v-bind for class support separate by space.<commit_after>import Parser, { linkParser } from '../parser';
import { setAttr, addClass, removeClass } from '../../dom';
import { each, isString, isArray, isObject, diff, warn } from '../../util';

/**
 * 处理 styleObject, 批量更新元素 style
 * @param   {Element}  element
 * @param   {String}   styleObject
 */
function updateStyle (element, styleObject) {
	var style = element.style;

	if (!isObject(styleObject)) {
		return warn('v-bind for style must be a type of Object', styleObject);
	}

	each(styleObject, function (value, property) {
		if (style[property] !== value) {
			style[property] = value;
		}
	});
}

/**
 * 支持空格分割的 addClass
 * @param   {Element}  element
 * @param   {String}   className
 * @param   {Boolean}  remove
 */
function handleClass (element, className, remove) {
	each(className.split(' '), function (cls) {
		if (remove) {
			removeClass(element, cls);
		} else {
			addClass(element, cls);
		}
	});
}

/**
 * 更新元素的 className
 * @param   {Element}  element
 * @param   {Mix}      classValue
 * @param   {Boolean}  remove
 */
function updateClass (element, classValue, remove) {
	if (isString(classValue)) {
		handleClass(element, classValue, remove);
	} else if (isArray(classValue)) {
		each(classValue, function (cls) {
			handleClass(element, cls, remove);
		});
	} else if (isObject(classValue)) {
		each(classValue, function (add, cls) {
			handleClass(element, cls, remove || !add);
		});
	}
}

/**
 * v-bind 指令解析模块
 */
export function VBind () {
	Parser.apply(this, arguments);
}

var vbind = linkParser(VBind);

/**
 * 解析 v-bind 指令
 */
vbind.parse = function () {
	this.desc.deep = true;
	this.bind();
}

/**
 * 视图更新
 * @param   {Mix}  newValue
 * @param   {Mix}  oldValue
 */
vbind.update = function (newValue, oldValue) {
	var type = this.desc.args;
	if (type) {
		this.single(type, newValue, oldValue);
	} else {
		this.multi(newValue, oldValue);
	}
}

/**
 * 解析单个 attribute
 * @param   {String}  type
 * @param   {Mix}     newValue
 * @param   {Mix}     oldValue
 */
vbind.single = function (type, newValue, oldValue) {
	switch (type) {
		case 'class':
			this.handleClass(newValue, oldValue);
			break;
		case 'style':
			this.handleStyle(newValue, oldValue);
			break;
		default:
			this.handleAttr(type, newValue, oldValue);
	}
}

/**
 * 解析 attribute, class, style 组合
 * @param   {Object}  newJson
 * @param   {Object}  oldJson
 */
vbind.multi = function (newJson, oldJson) {
	if (oldJson) {
		let { after, before } = diff(newJson, oldJson);
		this.batch(after, before);
	}

	this.batch(newJson);
}

/**
 * 绑定属性批处理
 * @param   {Object}  newObj
 * @param   {Object}  oldObj
 */
vbind.batch = function (newObj, oldObj) {
	each(newObj, function (value, key) {
		this.single(key, value, oldObj && oldObj[key]);
	}, this);
}

/**
 * 更新处理 className
 * @param   {Mix}  newClass
 * @param   {Mix}  oldClass
 */
vbind.handleClass = function (newClass, oldClass) {
	var el = this.el;

	// 数据更新
	if (oldClass) {
		let { after, before } = diff(newClass, oldClass);
		updateClass(el, before, true);
		updateClass(el, after);
	} else {
		updateClass(el, newClass);
	}
}

/**
 * 更新处理 style
 * @param   {Mix}  newStyle
 * @param   {Mix}  oldStyle
 */
vbind.handleStyle = function (newStyle, oldStyle) {
	var el = this.el;

	// 数据更新
	if (oldStyle) {
		// 移除旧样式(设为 null)
		each(oldStyle, function (v, key) {
			oldStyle[key] = null;
		});

		updateStyle(el, oldStyle);
	}

	updateStyle(el, newStyle);
}

/**
 * 更新处理 attribute
 * @param   {String}   attr
 * @param   {String}   newValue
 * @param   {String}   oldValue
 */
vbind.handleAttr = function (attr, newValue, oldValue) {
	setAttr(this.el, attr, newValue);
}<|endoftext|>


<commit_before>'use strict'

// Dependencies
var ipc 	= null;
var VERBS 	= ['GET', 'POST', 'UPDATE', 'DELETE'];

class Router {

	constructor( name, window ) {

		this._name = name;
		this._routes = {};
		this._window = window;

	}

	_common( argss, verb ){

		var args = Array.prototype.slice.call( argss, 0 );
		if( 1 === args.length ){
			throw new Error('Bad arguments, MUST provide a route and a callback')
		}

		var route = args.shift();
		var cb = args.pop();

		if( typeof cb === 'function' ){

			this._setupRoute( route );
			this._routes[ route ][ 'http' ][ verb.toUpperCase() ] = cb;

		}

	}

	_setupRoute( route ){

		if( this._routes.hasOwnProperty( route ) ){
			return;
		}

		this._routes[ route ] = {
			std: {
				_senders: [],
				_receivers: [],
			},
			http: {}
		};

	}

	send(){

		var args = Array.prototype.slice.call(arguments, 0);

		if( this._window ){
			this._window.send.apply( this._window, args || [] );
		}

		var routes = [args.shift()];
		if( routes[0] === '*' ){
			routes = routes.concat( Object.keys( this._routes ) );
		}else{
			routes = ['*'].concat( routes );
		}

		routes.forEach(function( route ){

			// Not registered
			if( this._routes.hasOwnProperty( route ) ){

				this._routes[ route ][ 'std' ][ '_receivers' ].forEach(function( cb ){

					cb.apply( null, args || [] );

				})

			}
		}, this)
	}

	on(){

		var args = Array.prototype.slice.call(arguments, 0);
		if( 1 === args.length ){
			throw new Error('Bad arguments, MUST provide a route and a callback')
		}

		var route = args.shift();
		var endCb = args.pop();

		if( typeof endCb === 'function' ){

			this._setupRoute( route );
			this._routes[ route ][ 'std' ][ '_receivers' ].push( endCb );

			if( ipc ){

				ipc.on( route, function(){

					var args = Array.prototype.slice.call(arguments, 1);
					endCb.apply( null, args );

				})

			}

		}

	}

	route(){

		var args = Array.prototype.slice.call(arguments, 0);
		if( 3 >  args.length ){
			throw new Error('Bad arguments, MUST provide a route, a method and a callback')
		}
		var route = args.shift();
		var verbs = [args.shift().toUpperCase()];
		var params= [];

		var len = args.length-1;
		var i 	= 0;
		while( i++ < len ){
			params.push( args.shift() );
		}

		var cb = args.pop();

		// Not registered
		if( !this._routes.hasOwnProperty( route ) ){
			return;
		}

		if( verbs[0] === '*' ){
			verbs = VERBS;
		}

		verbs.forEach(function( verb ){

			if( this._routes[ route ][ 'http' ][verb] &&
				typeof this._routes[ route ][ 'http' ][verb] === 'function'
			){

				this._routes[ route ][ 'http' ][ verb ].apply( null, [{
					method: verb,
					params: JSON.parse( JSON.stringify(params) )
				}, {
					json: function( err, obj ){
						if( arguments.length === 1 ){
							obj = err;
							err = null;
						}
						cb( err, JSON.parse( JSON.stringify( obj ) ) );
					}
				}])

			}//Skip

		}, this);

	}

	post(){

		this._common( arguments, 'POST' );

	}

	get(){

		this._common( arguments, 'GET' );

	}

	update(){

		this._common( arguments, 'UPDATE' );
	}

	delete(){

		this._common( arguments, 'DELETE' );

	}

}

//module.exports = Router;
var _router = null;
module.exports = function( name, window ){
	try{
		ipc = require('electron').ipcMain;
	}catch( e ){
		// Non electron environment
	}
	if( null === _router ){
		_router = new Router( name, window );
	}
	return _router;
}<commit_msg>Continue<commit_after>'use strict'

var ipc = null;
const VERBS  = ['GET', 'POST', 'UPDATE', 'DELETE'];
var CACHED = { std: [], http: {} };

const PROC_SIDES = { 'RENDERER': 0, 'MAIN': 1, TR: { 0: 'RENDERER', 1: 'MAIN' } };
const SIDE_EVTS = {
	0: { GET: 'ROUTER_REND_SET_ROUTES', SET: 'ROUTER_REND_GET_ROUTES' },
	1: { GET: 'ROUTER_MAIN_SET_ROUTES', SET: 'ROUTER_MAIN_GET_ROUTES' }
}
var PROC_SIDE = 'MAIN';

function _wrap( route ){
	var ret = {};
	Object.keys( route ).forEach( r => {
		ret[r] = {
			http: Object.keys( route[r].http ).map( h => {
				return h;
			})
		};
		if( route[r].std.length ){
			ret[r].std = route[r].std.length
		}
	})
	return JSON.stringify( ret );
}

function _storeOnCache( route ){
	route = JSON.parse( route );
	Object.keys( route ).forEach( r => {
		if( route[r].std && (-1 === CACHED.std.indexOf( r )) ){
			CACHED.std.push( r );
		}
		route[r].http.forEach( h => {
			if( (-1 === CACHED.http[h].indexOf( r )) ){
				CACHED.http[h].push( r );
			}
		})
	})
}

function _hashRouteListen( verb, route, back ){
	verb  = verb.trim().toUpperCase();
	route = route.trim()//;.toUpperCase();
	back = (back || false);
	if( verb === 'STD' || (3 > arguments.length)){
		return verb + '::' + route + '::' + PROC_SIDES.TR[PROC_SIDE];
	}else if( !back ){
		return verb + '::' + route + '::' + PROC_SIDES.TR[PROC_SIDE] + '::' + 'FORW';
	}else{
		return verb + '::' + route + '::' + PROC_SIDES.TR[1-PROC_SIDE] + '::' + 'BACK';
	}
}

function _hashRouteSend( verb, route, back ){
	verb  = verb.trim().toUpperCase();
	route = route.trim()//;.toUpperCase();
	back = (back || false);
	if( verb === 'STD' || (3 > arguments.length)){
		return verb + '::' + route + '::' + PROC_SIDES.TR[1-PROC_SIDE];
	}else if( !back ){
		return verb + '::' + route + '::' + PROC_SIDES.TR[1-PROC_SIDE] + '::' + 'FORW';
	}else{
		return verb + '::' + route + '::' + PROC_SIDES.TR[PROC_SIDE] + '::' + 'BACK';
	}
}

class Router {

	constructor( name, window ) {

		this._name = name;
		this._routes = {};
		this._window = window;

		// Prepare CACHE
		VERBS.forEach( verb => {
			CACHED.http[ verb ] = [];
		})

		this._setup();
	}

	_setup(){
		// Here we set the necessary callbacks for retrieving
		// other side events
		if( ipc ){
			var that = this;
			//console.log('[SETUP]', PROC_SIDE, 'LISTENING FOR', SIDE_EVTS[PROC_SIDE].GET);
			// Register a handler for retrieving other's side route
			ipc.on(SIDE_EVTS[PROC_SIDE].GET, function( event, routes ){
				_storeOnCache( routes );
				//console.log('RESTORE CACHE', CACHED);
			})
			//console.log('[SETUP]', PROC_SIDE, 'RETRIEVING FOR', SIDE_EVTS[1-PROC_SIDE].GET);
			ipc.on(SIDE_EVTS[1-PROC_SIDE].SET, function( event, routes ){
				that._sendCache();
			})
			this._requestCache();
		}
	}

	_requestCache(){

		// If we are on a different process "routes" is going to be empty
		// so no route is going to be fired, as every method registers on
		// ipc too, we can reconstruct the routes based on ipc channel
		// Reconstruct all routes
		//console.log('[SETUP]', PROC_SIDES.TR[PROC_SIDE], 'SENDING FOR', SIDE_EVTS[PROC_SIDE].SET);
		if( this._window ){
			this._window.send(SIDE_EVTS[PROC_SIDE].SET);
		}else{
			ipc.send(SIDE_EVTS[PROC_SIDE].SET);
		}

	}

	_sendCache(){

		if( this._window ){
			this._window.send( SIDE_EVTS[1-PROC_SIDE].GET, _wrap(this._routes) );
		}else{
			ipc.send( SIDE_EVTS[1-PROC_SIDE].GET, _wrap(this._routes) );
		}

	}

	_common( argss, verb ){

		var args = Array.prototype.slice.call( argss, 0 );
		if( 1 === args.length ){
			throw new Error('Bad arguments, MUST provide a route and a callback')
		}

		var route = args.shift();
		var cb = args.pop();
		verb = verb.toUpperCase();

		if( typeof cb === 'function' ){

			this._setupRoute( route );
			this._routes[ route ][ 'http' ][ verb ] = cb;

		}

		//console.log('Registering route over http', verb, route, _hashRouteListen( verb, route ));

		var that = this;

		if( ipc ){

			ipc.on( _hashRouteListen( verb, route ), function( event, req ){

				req = JSON.parse( req );
				//console.log('Inside receiver cb', req);
				req.push({
					json: function( err, obj ){
						if( arguments.length === 1 ){
							obj = err;
							err = null;
						}
						//console.log('sending to', this._window?'window':'ipc', _hashRouteSend( verb, route, true ));
						if( this._window ){
							this._window.send.apply(this._window, [_hashRouteSend( verb, route, true ), err].concat(JSON.parse(JSON.stringify( obj ))));
						}else{
							ipc.send.apply(ipc, [_hashRouteSend( verb, route, true ), err].concat(JSON.parse(JSON.stringify( obj ))));
						}
					}.bind(that)
				});
				cb.apply( that, req );

			});

		}

		this._sendCache();

	}

	_setupRoute( route ){

		if( this._routes.hasOwnProperty( route ) ){
			return;
		}

		this._routes[ route ] = {
			std: [],
			http: {}
		};

	}

	// SENDER
	send(){

		// Re-Cache, just in case...
		this._requestCache();

		var that = this;
		var fnArgs = arguments;

		setTimeout(function() {

			var args = Array.prototype.slice.call(fnArgs, 0);

			if( that._window ){
				that._window.send.apply( that._window, args || [] );
			}

			var routes = [args.shift()];
			if( routes[0] === '*' ){
				routes = routes.concat( Object.keys( that._routes ) );
			}else{
				routes = ['*'].concat( routes );
			}

			routes.forEach(function( route ){

				if( ipc && (-1 !== CACHED.std.indexOf(route) )){

					if( that._window ){
						that._window.send.apply(that._window, [_hashRouteSend( 'STD', route )].concat( JSON.stringify(args || []) ));
					}else{
						ipc.send.apply(ipc, [_hashRouteSend( 'STD', route )].concat( JSON.stringify(args || []) ));
					}

				}
				// Not registered
				if( that._routes.hasOwnProperty( route ) ){

					that._routes[ route ][ 'std' ].forEach(function( cb ){

						cb.apply( null, args || [] );

					})

				}
			}, that)

		}, 10);

	}

	// RECEIVER
	on(){

		var args = Array.prototype.slice.call(arguments, 0);
		if( 1 === args.length ){
			throw new Error('Bad arguments, MUST provide a route and a callback')
		}

		var route = args.shift();
		var endCb = args.pop();

		if( typeof endCb === 'function' ){

			this._setupRoute( route );
			this._routes[ route ][ 'std' ].push( endCb );

			if( ipc ){

				ipc.on( _hashRouteListen( 'STD', route ), function(){

					args = Array.prototype.slice.call(arguments, 1);
					endCb.apply( null, JSON.parse(args) );

				})

			}

		}

		this._sendCache();

	}

	// SENDER
	route(){

		var args = Array.prototype.slice.call(arguments, 0);
		if( 3 >  args.length ){
			throw new Error('Bad arguments, MUST provide a route, a method and a callback')
		}
		var route = args.shift();
		var verbs = [args.shift().toUpperCase()];
		var params= [];

		var len = args.length-1;
		var i 	= 0;
		while( i++ < len ){
			params.push( args.shift() );
		}

		var cb = args.pop();

		// Re-Cache, just in case...
		this._requestCache();

		var that = this;
		setTimeout(function() {

			if( verbs[0] === '*' ){
				verbs = VERBS;
			}

			verbs.forEach(function( verb ){

				var fnArgs = [{
					method: verb,
					params: JSON.parse( JSON.stringify(params) )
				}];

				//console.log('Routing', verb, route, _hashRouteSend( verb, route ), fnArgs);

				if( ipc && (-1 !== CACHED.http[verb].indexOf(route) )){

					ipc.once(_hashRouteListen( verb, route, true ), function(){
						var args = Array.prototype.slice.call( arguments, 1 );
						cb( args.splice(0, 1)[0], JSON.parse( JSON.stringify( args ) ) );
					})
					//console.log('send', 'registered back on', _hashRouteListen( verb, route, true ));
					if( that._window ){
						that._window.send.apply(that._window, [_hashRouteSend( verb, route )].concat( JSON.stringify(fnArgs || []) ));
					}else{
						ipc.send.apply(ipc, [_hashRouteSend( verb, route )].concat( JSON.stringify(fnArgs || []) ));
					}

				}
				if(
					that._routes.hasOwnProperty( route ) &&
					that._routes[ route ][ 'http' ][verb] &&
					typeof that._routes[ route ][ 'http' ][verb] === 'function'
				){

					fnArgs = fnArgs.concat({
						json: function( err, obj ){
							console.log('inner json route', err, obj, arguments);
							if( arguments.length === 1 ){
								obj = err;
								err = null;
							}
							cb( err, JSON.parse( JSON.stringify( obj ) ) );
						}
					})
					that._routes[ route ][ 'http' ][ verb ].apply( null, fnArgs );

				}// Not registered, skip on std router

			}, that);

		}, 10);

	}

	// RECEIVERS
	post(){

		this._common( arguments, 'POST' );

	}

	get(){

		this._common( arguments, 'GET' );

	}

	update(){

		this._common( arguments, 'UPDATE' );
	}

	delete(){

		this._common( arguments, 'DELETE' );

	}

}

//module.exports = Router;
var _router = null;
module.exports = function( name, window ){
	try{

		ipc = require('electron').ipcMain;

		if( ipc !== undefined ){
			// We are on main process
			PROC_SIDE = PROC_SIDES.MAIN;
		}else{
			ipc = require('electron').ipcRenderer;
			PROC_SIDE = PROC_SIDES.RENDERER;
		}

	}catch( e ){
		// Non electron environment
	}
	if( null === _router ){
		_router = new Router( name, window );
	}
	return _router;
}
<|endoftext|>


<commit_before>var mpass = require( "mpass" ),
	util = require( "keigai" ).util,
	nodemailer = require( "nodemailer" ),
	path = require( "path" ),
	config = require( path.join(__dirname, "config.json" ) ),
	HEADERS = {"cache-control": "no-cache" },
	SUCCESS = 200,
	INVALID = 400,
	FAILURE = 500,
	PASSWORDS = 1,
	PASSWORDS_MAX = config.max || 100,
	WORDS = 3,
	WORDS_MAX = 10,
	mta;

function email ( to, pass ) {
	var defer = util.defer();

	mta.sendMail( {
		from: config.email.from,
		to: to,
		subject: config.email.subject,
		text: config.email.text.replace( /\{\{password\}\}/g, pass ),
		html: config.email.html.replace( /\{\{password\}\}/g, pass.replace( /\n/g, "
" ) )
	}, function ( e, info ) {
		if ( e ) {
			console.error( e.stack || e.message || e );
			defer.reject( e );
		}
		else {
			defer.resolve( info.response );
		}
	} );

	return defer;
}

mta = nodemailer.createTransport( {
	host: config.email.host,
	port: config.email.port,
	secure: config.email.secure,
	auth: {
		user: config.email.user,
		pass: config.email.pass
	}
} );

module.exports.get = {
	"/": "POST to generate a password. Requires `words` to specify amount to use. Optional parameters are `email` to send as an Email, and `passwords` to generate a list."
};

module.exports.post = {
	"/": function ( req, res ) {
		var words = req.body.words === undefined ? WORDS : req.body.words,
			nth = req.body.passwords === undefined ? PASSWORDS : req.body.passwords,
			pass = [],
			i = -1,
			result;

		if ( typeof words !== "number" || words < 1 || typeof nth !== "number" || nth < 1 ) {
			res.error( INVALID, new Error( "Invalid arguments" ) );
		} else {
			words = words > WORDS_MAX ? WORDS_MAX : words;
			nth = nth > PASSWORDS_MAX ? PASSWORDS_MAX : nth;

			while ( ++i < nth ) {
				pass.push( mpass( words ) )
			}

			result = nth === 1 ? pass[ 0 ] : pass;

			if ( config.email.enabled && req.body.email ) {
				email( req.body.email, pass.join( "\n" ) ).then( function () {
					res.respond( result, SUCCESS, HEADERS );
				}, function ( e ) {
					res.error( FAILURE, e );
				} );
			} else {
				res.respond( result, SUCCESS, HEADERS );
			}
		}
	}
};
<commit_msg>Log last<commit_after>var mpass = require( "mpass" ),
	util = require( "keigai" ).util,
	nodemailer = require( "nodemailer" ),
	path = require( "path" ),
	config = require( path.join(__dirname, "config.json" ) ),
	HEADERS = {"cache-control": "no-cache" },
	SUCCESS = 200,
	INVALID = 400,
	FAILURE = 500,
	PASSWORDS = 1,
	PASSWORDS_MAX = config.max || 100,
	WORDS = 3,
	WORDS_MAX = 10,
	mta;

function email ( to, pass ) {
	var defer = util.defer();

	mta.sendMail( {
		from: config.email.from,
		to: to,
		subject: config.email.subject,
		text: config.email.text.replace( /\{\{password\}\}/g, pass ),
		html: config.email.html.replace( /\{\{password\}\}/g, pass.replace( /\n/g, "
" ) )
	}, function ( e, info ) {
		if ( e ) {
			defer.reject( e );
		} else {
			defer.resolve( info.response );
		}
	} );

	return defer;
}

mta = nodemailer.createTransport( {
	host: config.email.host,
	port: config.email.port,
	secure: config.email.secure,
	auth: {
		user: config.email.user,
		pass: config.email.pass
	}
} );

module.exports.get = {
	"/": "POST to generate a password. Requires `words` to specify amount to use. Optional parameters are `email` to send as an Email, and `passwords` to generate a list."
};

module.exports.post = {
	"/": function ( req, res ) {
		var words = req.body.words === undefined ? WORDS : req.body.words,
			nth = req.body.passwords === undefined ? PASSWORDS : req.body.passwords,
			pass = [],
			i = -1,
			result;

		if ( typeof words !== "number" || words < 1 || typeof nth !== "number" || nth < 1 ) {
			res.error( INVALID, new Error( "Invalid arguments" ) );
		} else {
			words = words > WORDS_MAX ? WORDS_MAX : words;
			nth = nth > PASSWORDS_MAX ? PASSWORDS_MAX : nth;

			while ( ++i < nth ) {
				pass.push( mpass( words ) )
			}

			result = nth === 1 ? pass[ 0 ] : pass;

			if ( config.email.enabled && req.body.email ) {
				email( req.body.email, pass.join( "\n" ) ).then( function () {
					res.respond( result, SUCCESS, HEADERS );
				}, function ( e ) {
					res.error( FAILURE, e );
					console.error( e.stack || e.message || e );
				} );
			} else {
				res.respond( result, SUCCESS, HEADERS );
			}
		}
	}
};
<|endoftext|>


<commit_before>/**
 * Created by 3er on 1/5/15.
 */

// Since Node 0.8, .existsSync() moved from path to fs:
var path = require('path');
var fs = require('fs');
var walk = require('walk');
var config = require('./config/oped');
var PRIVATE = require('./config/private');
var async = require('async');
var _existsSync = fs.existsSync || path.existsSync;

var _ = require('underscore');
var moment = require('moment');
var formidable = require('formidable');

var chokidar = require('chokidar');
var checklist = require('./checkVideoUrl').checklist;
var replace = require('./checkVideoUrl').replace;
// qiniu
var qiniu = require('qiniu')
qiniu.conf.ACCESS_KEY = PRIVATE.qiniu.access_key
qiniu.conf.SECRET_KEY = PRIVATE.qiniu.secret_key

var compress = require('./compress');

var generateURL = function (ver, key) {
    var deadline = Math.floor(Date.now() / 1000) + ver.expiration;
    var link = encodeURI('http://' + ver.domain + '/' + key + '?e=' + deadline);
    var token = qiniu.conf.ACCESS_KEY + ':' +
        qiniu.util.base64ToUrlSafe(qiniu.util.hmacSha1(link, qiniu.conf.SECRET_KEY));
    return link +
        '&token=' + token;
}

var generateInfoURL = function (ver, key) {
    var deadline = Math.floor(Date.now() / 1000) + ver.expiration;
    var link = encodeURI('http://' + ver.domain + '/' + key + '?avinfo&e=' + deadline);
    var token = qiniu.conf.ACCESS_KEY + ':' +
        qiniu.util.base64ToUrlSafe(qiniu.util.hmacSha1(link, qiniu.conf.SECRET_KEY));
    return link +
        '&token=' + token;
}

var generateCompressScripts = function (path, oped) {
    var cmd = compress.generate(path, oped);
    // console.log(cmd);
    return cmd;
}
var deleteAsync = function (key, cb) {
    var rmQiniu = function (reso, key, next) {
        var client = new qiniu.rs.Client();
        client.remove(PRIVATE.qiniu[reso].bucket, key, function (err) {
            if (err) {
                next(err)
            }
            else {
                //console.log('a')
                next()
            }
        });
    };

    var rmLocal = function (reso, key, next) {
        var filePath = config.dir.rsync + reso + '/' + key;
        fs.unlink(filePath, function (err) {
            if (err) {
                next(err);
            }
            else {
                // console.log('b')
                next();
            }
        });
    };
    async.parallel([
            function (next) {
                rmQiniu('origin', key, next)
            }, function (next) {
                rmQiniu('high', key, next)
            }, function (next) {
                rmQiniu('medium', key, next)
            }, function (next) {
                rmQiniu('low', key, next)
            }, function (next) {
                rmQiniu('mobile',key,next)
            },
            function (next) {
                rmLocal('originNew', key, next)
            }, function (next) {
                rmLocal('highNew', key, next)
            }, function (next) {
                rmLocal('mediumNew', key, next)
            }, function (next) {
                rmLocal('lowNew', key, next)
            },function(next){
                rmLocal('mobileNew',key,next)
            }
        ], cb
    );

}

var deleteList = [];

module.exports = function (app) {
    var testAdd = config.dir.rsync + 'mobileNew/';

    var watcher = chokidar.watch(testAdd, {ignored: /\.DS_Store/, persistent: true});

    //watcher.add(['/1.txt', '2.txt', '3.txt']);
    watcher.on('add', function (path) {
        var testArr = _.map(deleteList, function (item) {
            return testAdd + item;
        });
        var judger = _.find(testArr, function (asis) {
            return asis === path;
        });

        if (judger !== undefined) {
            var delKey = path.replace(/^.*[\/]/, '');
            deleteAsync(delKey, function (err, result) {
                if (err) {
                    console.log(err);
                }
                //reserved console log which indicates the delete process
                console.log('delete success: ' + path);
                var index = deleteList.indexOf(delKey);

                if (index > -1) {
                    deleteList.splice(index, 1);
                }
            });
        }
    });
    app.get('/checklist', function (req, res) {
        checklist(function (err, data) {
            if (err) {res.status(500).json(err);}
            else {
                res.status(200).json(data);
            }
        })

    });
    app.post('/replace', function (req, res) {
        var data = req.body;
        replace(data, function (err) {
            if (err) {
                res.status(500);
                res.end();
            }
            else {
                res.status(200);
                res.end();
            }

        })
    })

    // http api
    app.get('/video/opeds', function (req, res) {
        res.status(200).json(config.opeds);
    });

    app.post('/video/upload', function (req, res) {
        var dir = config.dir;
        // headers
        res.setHeader('Pragma', 'no-cache');
        res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
        res.setHeader('Content-Disposition', 'inline; filename="files.json"');

        // init
        var ret = {files: []};
        var form = new formidable.IncomingForm();
        form.encoding = 'utf-8';
        // 把mov转为mp4
        form.keepExtensions = false;

        var command = new compress.oped();

        // make upload directory
        form.uploadDir = dir.upload + moment().format('YYYYMMDDhhmmss/');

        // TODO: Exception判断
        fs.mkdirSync(form.uploadDir);

        // handle uplaod
        form.on('fileBegin', function (name, file) {
            var filter = new RegExp("[~!@#$^&*()=|{}':;',\\[\\].<>/?]");
            file.name = file.name.replace(/\.[^/.]+$/g, '').replace(/-/g, "_").replace(/\s+/g,'');
            if(filter.test(file.name)){
                ret.files[0].error = '视频名不能包含英文标点、括号（可以用中文输入法的标点，括号等）';
            }
            file.name = file.name + '.mp4';
            //console.log(file.name)
            file.path = form.uploadDir + file.name;

            ret.files.push({name: file.name, path: file.path});
            if (_existsSync(file.path) || _existsSync(config.dir.rsync + 'originNew/' + file.name)) {
                ret.files[0].error = '文件已存在，不能覆盖';
                //console.log(ret.files[0].error);
            }
        }).on('field', function (name, value) {
            // 生成片头片尾命令
            command[name] = value;
        }).on('file', function (name, file) {
//                console.log(file.path);
            ret.files[0].size = file.size;
        }).on('aborted', function () {
            ret.files.forEach(function (file) {
                fs.unlinkSync(file.path);
            });
            fs.rmdirSync(path.dirname(ret.files[0].path));
            //console.log('删除文件夹')
        }).on('error', function (e) {
            ret.files[0].error = e;
            // console.log(e);
        }).on('progress', function (bytesReceived) {
        }).on('end', function () {
            var error = ret.files[0].error;
	    if (!error) {
            res.status(201).json(ret);
            if (_existsSync(form.uploadDir)) {
                generateCompressScripts(ret.files[0].path, command)
            }
        }else{
            ret.files.forEach(function (file) {
                fs.unlinkSync(file.path);
            });
            fs.rmdir(path.dirname(ret.files[0].path));
            res.status(500).json(error);
        }
        }).parse(req);
    });

    app.get('/qiniu/link/origin/:key', function (req, res) {
        var l = generateURL(PRIVATE.qiniu['origin'], req.param('key'), qiniu);
        res.redirect(l);
    });

    app.get('/qiniu/info/origin/:key', function (req, res) {
//        console.log(req.param('ver'));
//        console.log(req.param('key'));
        var l = generateInfoURL(PRIVATE.qiniu['high'], req.param('key'), qiniu);
        res.redirect(l);
    });

    app.post('/qiniu/list', function (req, res) {
        var marker = null;
        qiniu.rsf.listPrefix(PRIVATE.qiniu.origin.bucket, '', marker, 999999, function (err, ret) {
            if (err) {
                res.status(500).send(err);
                console.log(err);
            } else {
                // process ret.marker & ret.items
//           console.log(ret.marker);
//          console.log(ret.items);

                var retr = _.chain(ret.items)
                    .sortBy(function (item) {
                        return item.key;
                    })
//                    .each(function (item) {
//                        item.link = generateURL(item, qiniu, PRIVATE.origin)
//                    })
                    .value();
                res.status(200).send({
                    current: 1,
                    rowCount: -1,
                    rows: retr,
                    total: retr.length
                });
            }
        });
    });
    app.delete('/qiniu/list/:key', function (req, res) {
        var key = req.params.key;
        deleteAsync(key, function (err) {

            if (err) console.log(err);
            res.status(200);
            res.end('delete success')

        });

    });

    app.post('/video/compressing/:key', function (req, res) {
        deleteList.push(req.params.key);
        _.uniq(deleteList);
        res.status(201);
        res.end('cancel success');
    });

    app.post('/video/compressing', function (req, res) {
        // mock
        var arr = [];
        var filters = [
<<<<<<< HEAD
            '.DS_Store', 'command','outputOri.mp4','outputH.mp4','outputL.mp4','outputM.mp4','outputMo.mp4','mktoutputH.mp4','mktoutputL.mp4',"mktoutputM.mp4"
=======
            '.DS_Store', 'command','outputOri.mp4','outputH.mp4','outputL.mp4','outputM.mp4','outputMo.mp4','mktoutputH.mp4',
            'mktoutputL.mp4',"mktoutputM.mp4"
>>>>>>> ec8a991948fb7ae72561013a543b0b2fdc7ca11f
        ]

        var options = {
            listeners: {
                names: function (root, nodeNamesArray) {
                    _.chain(nodeNamesArray)
                        .flatten()
                        .difference(filters)
                        .reject(function (item) {
                            return (item.length == 14) && (item.indexOf('201') == 0);
                        })
                        .each(function (item) {
                            arr.push({key: item, progress: "compress"})
                        });
                }, directories: function (root, dirStatsArray, next) {
                    next();
                }, files: function (root, fileStats, next) {
                    next();
                }, errors: function (root, nodeStatsArray, next) {
                    next();
                }
            }
        };

        walker = walk.walkSync(config.dir.upload, options);

//        console.log("all done");

        var retr = arr;
        var tempKeys = _.object(deleteList, ['']);
        var temp = _.filter(retr, function (item) {
            return !(item.key in tempKeys);
        });
//            _.chain(arr)
//            .sortBy(function (item) {
//                return item.progress;
//            })
//            .value();

        res.status(200).send({
            current: 1,
            rowCount: -1,
            rows: temp,
            total: 2
        });
    });
}
<commit_msg>fix merge conflicts<commit_after>/**
 * Created by 3er on 1/5/15.
 */

// Since Node 0.8, .existsSync() moved from path to fs:
var path = require('path');
var fs = require('fs');
var walk = require('walk');
var config = require('./config/oped');
var PRIVATE = require('./config/private');
var async = require('async');
var _existsSync = fs.existsSync || path.existsSync;

var _ = require('underscore');
var moment = require('moment');
var formidable = require('formidable');

var chokidar = require('chokidar');
var checklist = require('./checkVideoUrl').checklist;
var replace = require('./checkVideoUrl').replace;
// qiniu
var qiniu = require('qiniu')
qiniu.conf.ACCESS_KEY = PRIVATE.qiniu.access_key
qiniu.conf.SECRET_KEY = PRIVATE.qiniu.secret_key

var compress = require('./compress');

var generateURL = function (ver, key) {
    var deadline = Math.floor(Date.now() / 1000) + ver.expiration;
    var link = encodeURI('http://' + ver.domain + '/' + key + '?e=' + deadline);
    var token = qiniu.conf.ACCESS_KEY + ':' +
        qiniu.util.base64ToUrlSafe(qiniu.util.hmacSha1(link, qiniu.conf.SECRET_KEY));
    return link +
        '&token=' + token;
}

var generateInfoURL = function (ver, key) {
    var deadline = Math.floor(Date.now() / 1000) + ver.expiration;
    var link = encodeURI('http://' + ver.domain + '/' + key + '?avinfo&e=' + deadline);
    var token = qiniu.conf.ACCESS_KEY + ':' +
        qiniu.util.base64ToUrlSafe(qiniu.util.hmacSha1(link, qiniu.conf.SECRET_KEY));
    return link +
        '&token=' + token;
}

var generateCompressScripts = function (path, oped) {
    var cmd = compress.generate(path, oped);
    // console.log(cmd);
    return cmd;
}
var deleteAsync = function (key, cb) {
    var rmQiniu = function (reso, key, next) {
        var client = new qiniu.rs.Client();
        client.remove(PRIVATE.qiniu[reso].bucket, key, function (err) {
            if (err) {
                next(err)
            }
            else {
                //console.log('a')
                next()
            }
        });
    };

    var rmLocal = function (reso, key, next) {
        var filePath = config.dir.rsync + reso + '/' + key;
        fs.unlink(filePath, function (err) {
            if (err) {
                next(err);
            }
            else {
                // console.log('b')
                next();
            }
        });
    };
    async.parallel([
            function (next) {
                rmQiniu('origin', key, next)
            }, function (next) {
                rmQiniu('high', key, next)
            }, function (next) {
                rmQiniu('medium', key, next)
            }, function (next) {
                rmQiniu('low', key, next)
            }, function (next) {
                rmQiniu('mobile',key,next)
            },
            function (next) {
                rmLocal('originNew', key, next)
            }, function (next) {
                rmLocal('highNew', key, next)
            }, function (next) {
                rmLocal('mediumNew', key, next)
            }, function (next) {
                rmLocal('lowNew', key, next)
            },function(next){
                rmLocal('mobileNew',key,next)
            }
        ], cb
    );

}

var deleteList = [];

module.exports = function (app) {
    var testAdd = config.dir.rsync + 'mobileNew/';

    var watcher = chokidar.watch(testAdd, {ignored: /\.DS_Store/, persistent: true});

    //watcher.add(['/1.txt', '2.txt', '3.txt']);
    watcher.on('add', function (path) {
        var testArr = _.map(deleteList, function (item) {
            return testAdd + item;
        });
        var judger = _.find(testArr, function (asis) {
            return asis === path;
        });

        if (judger !== undefined) {
            var delKey = path.replace(/^.*[\/]/, '');
            deleteAsync(delKey, function (err, result) {
                if (err) {
                    console.log(err);
                }
                //reserved console log which indicates the delete process
                console.log('delete success: ' + path);
                var index = deleteList.indexOf(delKey);

                if (index > -1) {
                    deleteList.splice(index, 1);
                }
            });
        }
    });
    app.get('/checklist', function (req, res) {
        checklist(function (err, data) {
            if (err) {res.status(500).json(err);}
            else {
                res.status(200).json(data);
            }
        })

    });
    app.post('/replace', function (req, res) {
        var data = req.body;
        replace(data, function (err) {
            if (err) {
                res.status(500);
                res.end();
            }
            else {
                res.status(200);
                res.end();
            }

        })
    })

    // http api
    app.get('/video/opeds', function (req, res) {
        res.status(200).json(config.opeds);
    });

    app.post('/video/upload', function (req, res) {
        var dir = config.dir;
        // headers
        res.setHeader('Pragma', 'no-cache');
        res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
        res.setHeader('Content-Disposition', 'inline; filename="files.json"');

        // init
        var ret = {files: []};
        var form = new formidable.IncomingForm();
        form.encoding = 'utf-8';
        // 把mov转为mp4
        form.keepExtensions = false;

        var command = new compress.oped();

        // make upload directory
        form.uploadDir = dir.upload + moment().format('YYYYMMDDhhmmss/');

        // TODO: Exception判断
        fs.mkdirSync(form.uploadDir);

        // handle uplaod
        form.on('fileBegin', function (name, file) {
            var filter = new RegExp("[~!@#$^&*()=|{}':;',\\[\\].<>/?]");
            file.name = file.name.replace(/\.[^/.]+$/g, '').replace(/-/g, "_").replace(/\s+/g,'');
            if(filter.test(file.name)){
                ret.files[0].error = '视频名不能包含英文标点、括号（可以用中文输入法的标点，括号等）';
            }
            file.name = file.name + '.mp4';
            //console.log(file.name)
            file.path = form.uploadDir + file.name;

            ret.files.push({name: file.name, path: file.path});
            if (_existsSync(file.path) || _existsSync(config.dir.rsync + 'originNew/' + file.name)) {
                ret.files[0].error = '文件已存在，不能覆盖';
                //console.log(ret.files[0].error);
            }
        }).on('field', function (name, value) {
            // 生成片头片尾命令
            command[name] = value;
        }).on('file', function (name, file) {
//                console.log(file.path);
            ret.files[0].size = file.size;
        }).on('aborted', function () {
            ret.files.forEach(function (file) {
                fs.unlinkSync(file.path);
            });
            fs.rmdirSync(path.dirname(ret.files[0].path));
            //console.log('删除文件夹')
        }).on('error', function (e) {
            ret.files[0].error = e;
            // console.log(e);
        }).on('progress', function (bytesReceived) {
        }).on('end', function () {
            var error = ret.files[0].error;
	    if (!error) {
            res.status(201).json(ret);
            if (_existsSync(form.uploadDir)) {
                generateCompressScripts(ret.files[0].path, command)
            }
        }else{
            ret.files.forEach(function (file) {
                fs.unlinkSync(file.path);
            });
            fs.rmdir(path.dirname(ret.files[0].path));
            res.status(500).json(error);
        }
        }).parse(req);
    });

    app.get('/qiniu/link/origin/:key', function (req, res) {
        var l = generateURL(PRIVATE.qiniu['origin'], req.param('key'), qiniu);
        res.redirect(l);
    });

    app.get('/qiniu/info/origin/:key', function (req, res) {
//        console.log(req.param('ver'));
//        console.log(req.param('key'));
        var l = generateInfoURL(PRIVATE.qiniu['high'], req.param('key'), qiniu);
        res.redirect(l);
    });

    app.post('/qiniu/list', function (req, res) {
        var marker = null;
        qiniu.rsf.listPrefix(PRIVATE.qiniu.origin.bucket, '', marker, 999999, function (err, ret) {
            if (err) {
                res.status(500).send(err);
                console.log(err);
            } else {
                // process ret.marker & ret.items
//           console.log(ret.marker);
//          console.log(ret.items);

                var retr = _.chain(ret.items)
                    .sortBy(function (item) {
                        return item.key;
                    })
//                    .each(function (item) {
//                        item.link = generateURL(item, qiniu, PRIVATE.origin)
//                    })
                    .value();
                res.status(200).send({
                    current: 1,
                    rowCount: -1,
                    rows: retr,
                    total: retr.length
                });
            }
        });
    });
    app.delete('/qiniu/list/:key', function (req, res) {
        var key = req.params.key;
        deleteAsync(key, function (err) {

            if (err) console.log(err);
            res.status(200);
            res.end('delete success')

        });

    });

    app.post('/video/compressing/:key', function (req, res) {
        deleteList.push(req.params.key);
        _.uniq(deleteList);
        res.status(201);
        res.end('cancel success');
    });

    app.post('/video/compressing', function (req, res) {
        // mock
        var arr = [];
        var filters = [
            '.DS_Store', 'command','outputOri.mp4','outputH.mp4','outputL.mp4','outputM.mp4','outputMo.mp4','mktoutputH.mp4','mktoutputL.mp4',"mktoutputM.mp4"
        ]

        var options = {
            listeners: {
                names: function (root, nodeNamesArray) {
                    _.chain(nodeNamesArray)
                        .flatten()
                        .difference(filters)
                        .reject(function (item) {
                            return (item.length == 14) && (item.indexOf('201') == 0);
                        })
                        .each(function (item) {
                            arr.push({key: item, progress: "compress"})
                        });
                }, directories: function (root, dirStatsArray, next) {
                    next();
                }, files: function (root, fileStats, next) {
                    next();
                }, errors: function (root, nodeStatsArray, next) {
                    next();
                }
            }
        };

        walker = walk.walkSync(config.dir.upload, options);

//        console.log("all done");

        var retr = arr;
        var tempKeys = _.object(deleteList, ['']);
        var temp = _.filter(retr, function (item) {
            return !(item.key in tempKeys);
        });
//            _.chain(arr)
//            .sortBy(function (item) {
//                return item.progress;
//            })
//            .value();

        res.status(200).send({
            current: 1,
            rowCount: -1,
            rows: temp,
            total: 2
        });
    });
}
<|endoftext|>


<commit_before>'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) {
    let start = moment('2016 04 11', 'YYYY MM DD'),
        now = moment('');
    var week = (Math.floor(now.diff(start, 'days') / 7) + 1) || 1;
    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/result', function(req, res) {

    if (req.user) {
      if (req.body.score.match(/[0-9]{1,2}-[0-9]{1,2}/)) {
        models.Match.update({
          score: req.body.score || null
        }, {
          where: [{ id: req.body.mid }, { season: 2016 }]
        }).then(function(rows) {
          res.send(rows == 1);
        }).catch(function(e) {
          res.send(e);
        })
      } else {
        res.send(false);
      }

    } else {
      res.sendStatus(403);
    }
  })

}<commit_msg>fix bug in calculating current week<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) {
    let start = moment('2016 04 11', 'YYYY MM DD'),
        now = moment();
    var week = (Math.floor(now.diff(start, 'days') / 7) + 1) || 1;
    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/result', function(req, res) {

    if (req.user) {
      if (req.body.score.match(/[0-9]{1,2}-[0-9]{1,2}/)) {
        models.Match.update({
          score: req.body.score || null
        }, {
          where: [{ id: req.body.mid }, { season: 2016 }]
        }).then(function(rows) {
          res.send(rows == 1);
        }).catch(function(e) {
          res.send(e);
        })
      } else {
        res.send(false);
      }

    } else {
      res.sendStatus(403);
    }
  })

}<|endoftext|>


<commit_before>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('/rawMSC', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('scratchTools/dumpMSC.jade');
});
*/

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 = JSON.parse(req.body.cycleString),
		i,
		steps = [],
		durations = [];

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

	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 +"] " + steps[i]]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"] " + durations[i]]);
	}

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

	return res.redirect('/PPG');
});<commit_msg>Cycle loading<commit_after>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('/rawMSC', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('scratchTools/dumpMSC.jade');
});
*/

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 = JSON.parse(req.body.cycleString),
		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');
	}

	//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', "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 +"] " + steps[i]]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"] " + durations[i]]);
	}

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

	return res.redirect('/PPG');
});<|endoftext|>


<commit_before>const monk = require('monk');
const wrap = require('co-monk');
const db = monk('localhost/github-dating');

const root = function* () {
  this.body = yield { text: 'hello world' };
};

const listContributors = function* () {
  const contributors = wrap(db.get('contributors'));
  this.body = yield contributors.find({});
};

const listProjects = function* () {
  const projects = wrap(db.get('projects'));
  this.body = yield projects.find({});
};

const findProject = function* (name) {
  const projects = wrap(db.get('projects'));
  this.body = yield projects.findOne({ username: name });
};

const findContributor = function* (name) {
  const contributors = wrap(db.get('contributors'));
  this.body = yield contributors.findOne({ username: name });
};

module.exports = {
  root,
  listProjects,
  findProject,
  listContributors,
  findContributor
};
<commit_msg>abstract route functions to remove duplications<commit_after>const monk = require('monk');
const wrap = require('co-monk');
const db = monk('localhost/github-dating');

const find = function (doc, field) {
  return function* (value) {
    const wrappedDoc = wrap(db.get(doc));
    const query = {};
    if (field) {
      query[field] = value;
    }
    this.body = yield wrappedDoc.find(query);
  };
};

const root = function* () {
  this.body = yield { text: 'hello world' };
};

module.exports = {
  root,
  listProjects: find('projects'),
  findProject: find('projects', 'username'),
  listContributors: find('contributors'),
  findContributor: find('contributors', 'username')
};
<|endoftext|>


<commit_before>require.paths.unshift('./vendor')
var nstore = require('nstore').extend(require('nstore/query')())
var fs = require('fs')
var haml = require('haml')
var clutch = require('clutch')

var terms = nstore.new('./db/terms.db')

var header = haml(fs.readFileSync('views/layouts/header.haml', 'utf8'))
var application = haml(fs.readFileSync('views/layouts/application.haml', 'utf8'))

function static(req, res, dir, file) {
	fs.readFile('./public/' + dir + '/' + file, function (err, data) {
		if (err) {
			res.writeHead(404, {'Content-Type': 'text/html'})
		} else {
			if (dir == 'scripts') {
				res.writeHead(200, {'Content-Type': 'text/javascript'})
			} else if (dir == 'stylesheets') {
				res.writeHead(200, {'Content-Type': 'text/css'})
			} else {
				res.writeHead(200, {'Content-Type': 'text/html'})
			}
			res.write(data)
		}
		res.end()
	})
}

function landing(req, res) {
	res.writeHead(200, {'Content-Type': 'text/html'})
	res.end(header({ yield: application() }))
}

function get_terms(req, res) {
	terms.all(function (err, results) {
		if (err) {
			res.writeHead(500, "Failed to get terms.", {'Content-Type': 'text/html'})
		} else {
			res.writeHead(200, "OK", {'Content-Type': 'text/html'})
			res.write(JSON.stringify(results))
		}
		res.end()
	})
}

function save_term(req, res) {
	req.on('data', function(chunk) {
		var term = require('querystring').parse(chunk).term
		if (term) {
			terms.save(null, {'term': term}, function (err) {
				if (err) {
					res.writeHead(500, "Failed to save term.", {'Content-Type': 'text/html'})
				} else {
					res.writeHead(200, "OK", {'Content-Type': 'text/html'})
				}
				res.end()
			})
		} else {
			res.writeHead(500, "Missing term.", {'Content-Type': 'text/html'})
			res.end()
		}
	})
}

exports.urls = clutch.route404([['GET /$', landing],
								['GET /terms$', get_terms],
								['POST /terms$', save_term],
								['GET /(.*)/(.*)$', static]])
<commit_msg>remove a term<commit_after>require.paths.unshift('./vendor')
var nstore = require('nstore').extend(require('nstore/query')())
var fs = require('fs')
var haml = require('haml')
var clutch = require('clutch')

var terms = nstore.new('./db/terms.db')

var header = haml(fs.readFileSync('views/layouts/header.haml', 'utf8'))
var application = haml(fs.readFileSync('views/layouts/application.haml', 'utf8'))

function static(req, res, dir, file) {
	fs.readFile('./public/' + dir + '/' + file, function (err, data) {
		if (err) {
			res.writeHead(404, {'Content-Type': 'text/html'})
		} else {
			if (dir == 'scripts') {
				res.writeHead(200, {'Content-Type': 'text/javascript'})
			} else if (dir == 'stylesheets') {
				res.writeHead(200, {'Content-Type': 'text/css'})
			} else {
				res.writeHead(200, {'Content-Type': 'text/html'})
			}
			res.write(data)
		}
		res.end()
	})
}

function landing(req, res) {
	res.writeHead(200, {'Content-Type': 'text/html'})
	res.end(header({ yield: application() }))
}

function get_terms(req, res) {
	terms.all(function (err, results) {
		if (err) {
			res.writeHead(500, "Failed to get terms.", {'Content-Type': 'text/html'})
		} else {
			res.writeHead(200, "OK", {'Content-Type': 'text/html'})
			res.write(JSON.stringify(results))
		}
		res.end()
	})
}

function save_term(req, res) {
	req.on('data', function(chunk) {
		var term = require('querystring').parse(chunk).term
		if (term) {
			terms.save(null, {'term': term}, function (err) {
				if (err) {
					res.writeHead(500, "Failed to save term.", {'Content-Type': 'text/html'})
				} else {
					res.writeHead(201, "OK", {'Content-Type': 'text/html'})
				}
				res.end()
			})
		} else {
			res.writeHead(500, "Missing term.", {'Content-Type': 'text/html'})
			res.end()
		}
	})
}

function remove_term(req, res, key) {
	terms.remove(key, function (err) {
		if (err) {
			res.writeHead(500, "Failed to remove term.", {'Content-Type': 'text/html'})
		} else {
			res.writeHead(200, "OK", {'Content-Type': 'text/html'})
		}
		res.end()
	})
}

exports.urls = clutch.route404([['GET /$', landing],
								['GET /terms$', get_terms],
								['POST /terms$', save_term],
								['DELETE /terms/(.*)$', remove_term],
								['GET /(.*)/(.*)$', static]])
<|endoftext|>


<commit_before>Router.route('/', function () {
  this.render('hello', {
    data: function () { return Items.findOne({_id: this.params._id}); }
  });
});

//// Example route
//Router.route('/', function () {
//  this.render('hello', {
//    data: function () { return Items.findOne({_id: this.params._id}); }
//  });
//});
<commit_msg>Added 'me' route.<commit_after>Router.route('/', function () {
  this.render('hello', {
    data: function () { return Items.findOne({_id: this.params._id}); }
  });
});

Router.route('/me');

//// Example route
//Router.route('/', function () {
//  this.render('hello', {
//    data: function () { return Items.findOne({_id: this.params._id}); }
//  });
//});
<|endoftext|>


<commit_before>'use babel';
'use strict';

import Command from '../Command';
import { inspect } from 'util';

export default class Eval extends Command
{
	constructor(bot)
	{
		super(bot, {
			name: 'eval',
			aliases: ['e'],
			description: 'Evaluate provided Javascript code',
			usage: '<prefix>eval [code]',
			extraHelp: '',
			group: 'base',
			stringArgs: true,
			ownerOnly: true
		});
	}

	async action(message, args)
	{
		const code = args.join(' ');
		if (!code) return this._respond(message, '**ERROR:** ```xl\nNo code provided to evaluate.\n```');

		try
		{
			var evaled = eval(code);
			if (typeof evaled !== 'string')	evaled = inspect(evaled, { depth: 0 });
			return this._respond(
				`**INPUT:**\n\`\`\`js\n${code}\n\`\`\`\n**OUTPUT:**\n\`\`\`xl\n${this._clean(evaled)}\n\`\`\``);
		}
		catch (err)
		{
			return this._respond(
				`**INPUT:**\n\`\`\`js\n${code}\n\`\`\`\n**ERROR:**\n\`\`\`xl\n${this._clean(evaled)}\n\`\`\``);
		}
	}

	_clean(text)
	{
		return typeof text === 'string' ? text
			.replace(/`/g, `\`${String.fromCharCode(8203)}`)
			.replace(/@/g, `@${String.fromCharCode(8203)}`)
			.replace(/[\w\d]{24}\.[\w\d]{6}\.[\w\d-_]{27}/g, '[REDACTED]')
			.replace(/email: '[^']+'/g, `email: '[REDACTED]'`)
			: text;
	}
}
<commit_msg>Fix eval command again<commit_after>'use babel';
'use strict';

import Command from '../Command';
import { inspect } from 'util';

export default class Eval extends Command
{
	constructor(bot)
	{
		super(bot, {
			name: 'eval',
			aliases: ['e'],
			description: 'Evaluate provided Javascript code',
			usage: '<prefix>eval [code]',
			extraHelp: '',
			group: 'base',
			stringArgs: true,
			ownerOnly: true
		});
	}

	async action(message, args)
	{
		const code = args.join(' ');
		if (!code) return this._respond(message, '**ERROR:** ```xl\nNo code provided to evaluate.\n```');

		try
		{
			var evaled = eval(code);
			if (typeof evaled !== 'string')	evaled = inspect(evaled, { depth: 0 });
			return this._respond(message,
				`**INPUT:**\n\`\`\`js\n${code}\n\`\`\`\n**OUTPUT:**\n\`\`\`xl\n${this._clean(evaled)}\n\`\`\``);
		}
		catch (err)
		{
			return this._respond(message,
				`**INPUT:**\n\`\`\`js\n${code}\n\`\`\`\n**ERROR:**\n\`\`\`xl\n${this._clean(evaled)}\n\`\`\``);
		}
	}

	_clean(text)
	{
		return typeof text === 'string' ? text
			.replace(/`/g, `\`${String.fromCharCode(8203)}`)
			.replace(/@/g, `@${String.fromCharCode(8203)}`)
			.replace(/[\w\d]{24}\.[\w\d]{6}\.[\w\d-_]{27}/g, '[REDACTED]')
			.replace(/email: '[^']+'/g, `email: '[REDACTED]'`)
			: text;
	}
}
<|endoftext|>