<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _logging = require('./logging');

var _actions = require('./actions');

var _ravenJs = require('raven-js');

var _ravenJs2 = _interopRequireDefault(_ravenJs);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var handlePolling = function handlePolling(store) {
  var running = true;
  var timeoutID = null;

  var checkForCaptcha = function checkForCaptcha(body) {
    if (body.indexOf('CAPTCHA') > -1) {
      store.dispatch((0, _actions.captchaRequired)());
    }
  };

  var checkForWork = function checkForWork(data) {
    if (data.work_available) {
      if (typeof data.url !== 'string') {
        var msg = 'work_available endpoint gave unexpected response: ' + JSON.stringify(data);
        throw new Error(msg);
      }

      store.dispatch((0, _actions.assignWork)({ url: data.url }));
    }
  };

  var ping = function ping(url) {
    var urlWithInfo = url;
    var profileInfo = store.getState().worker.get('profileInfo');
    if (profileInfo) {
      urlWithInfo = url + '?info=' + JSON.stringify(profileInfo);
    }
    (0, _logging.logDebug)('Pinging ' + urlWithInfo + '...');

    fetch(urlWithInfo).then(function (resp) {
      if (resp.ok) {
        resp.json().then(checkForWork);
      } else {
        resp.text().then(checkForCaptcha);
      }
    }).catch(function (err) {
      _ravenJs2.default.captureException(err);
    });
  };

  var shouldPing = function shouldPing(_ref) {
    var polling = _ref.polling;
    var worker = _ref.worker;
    return polling.get('polling') && polling.get('pollUrl') && worker.get('state') === 'ready';
  };

  var tick = function tick() {
    if (!running) {
      return;
    }

    var state = store.getState();
    if (shouldPing(state)) {
      ping(state.polling.get('pollUrl'));
    } else {
      (0, _logging.logDebug)('Not pinging work server');
    }
    timeoutID = setTimeout(tick, state.polling.get('interval'));
  };

  // This is really for testing; in general polling shouldn't be stopped
  // directly (instead it should be controlled through reducers).
  var stop = function stop() {
    running = false;
    if (timeoutID) {
      clearTimeout(timeoutID);
    }
  };

  timeoutID = setTimeout(tick);

  return {
    stop: stop
  };
};

exports.default = handlePolling;<commit_msg>Check in the build<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _logging = require('./logging');

var _actions = require('./actions');

var _ravenJs = require('raven-js');

var _ravenJs2 = _interopRequireDefault(_ravenJs);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var handlePolling = function handlePolling(store) {
  var running = true;
  var timeoutID = null;

  var checkForCaptcha = function checkForCaptcha(body) {
    if (body.indexOf('CAPTCHA') > -1) {
      store.dispatch((0, _actions.captchaRequired)());
    }
  };

  var checkForWork = function checkForWork(data) {
    if (data.work_available) {
      if (typeof data.url !== 'string') {
        var msg = 'work_available endpoint gave unexpected response: ' + JSON.stringify(data);
        throw new Error(msg);
      }

      store.dispatch((0, _actions.assignWork)({ url: data.url }));
    }
  };

  var ping = function ping(url) {
    var urlWithInfo = url;
    var profileInfo = store.getState().worker.get('profileInfo');
    if (profileInfo) {
      urlWithInfo = url + '?info=' + JSON.stringify(profileInfo);
    }
    (0, _logging.logDebug)('Pinging ' + urlWithInfo + '...');

    fetch(urlWithInfo).then(function (resp) {
      if (resp.ok) {
        resp.json().then(checkForWork);
      } else {
        resp.text().then(checkForCaptcha);
      }
    }).catch(function (err) {
      _ravenJs2.default.captureException(err, { extra: { url: url } });
    });
  };

  var shouldPing = function shouldPing(_ref) {
    var polling = _ref.polling;
    var worker = _ref.worker;
    return polling.get('polling') && polling.get('pollUrl') && worker.get('state') === 'ready';
  };

  var tick = function tick() {
    if (!running) {
      return;
    }

    var state = store.getState();
    if (shouldPing(state)) {
      ping(state.polling.get('pollUrl'));
    } else {
      (0, _logging.logDebug)('Not pinging work server');
    }
    timeoutID = setTimeout(tick, state.polling.get('interval'));
  };

  // This is really for testing; in general polling shouldn't be stopped
  // directly (instead it should be controlled through reducers).
  var stop = function stop() {
    running = false;
    if (timeoutID) {
      clearTimeout(timeoutID);
    }
  };

  timeoutID = setTimeout(tick);

  return {
    stop: stop
  };
};

exports.default = handlePolling;<|endoftext|>


<commit_before>var parser   = require(__dirname+"/../lib/parser.js").parser.parse;
var compiler = require(__dirname+"/../lib/compiler.js").compiler;
var _        = require("./vendor/underscore");
var vm       = require("vm");

function Bluemold(input, data, templateName){
  var sandbox = {
        _ : _,
        $data : data
      },
      compiled, parsed;

  try { parsed = parser(input); }
  catch (e) { return errorMessage(e, input, templateName); }

  try {
    compiled = compiler(parsed);

    _.extend(sandbox, data);
    sandbox.Bluemold = function(i, context, templateName){
      return Bluemold(i, data, templateName);
    };

    return vm.createScript(compiled).runInNewContext(sandbox, "BluemoldTemplate");

  } catch (error) {
    return errorMessage(error, input, templateName, compiled);
  }
}

function errorMessage(e, input, templateName, compiled) {
  e.source   = input;
  e.template = templateName;
  if(e.stack && compiled){
    var stack         = e.stack.split(/\n/ig)[1];
    var errorPosition = (stack.match(/\d+$/) || [0])[0];
    if(errorPosition){
      e.lineNumber = (compiled.substr(0,errorPosition).match(/\\n/ig) || []).length+1;
    }
  }

  return e;
}

exports.Bluemold = Bluemold;
<commit_msg>Fix parser error messages<commit_after>var parser   = require(__dirname+"/../lib/parser.js").parser;
var compiler = require(__dirname+"/../lib/compiler.js").compiler;
var _        = require("./vendor/underscore");
var vm       = require("vm");

function Bluemold(input, data, templateName){
  var sandbox = {
        _ : _,
        $data : data
      },
      compiled, parsed;

  try { parsed = parser.parse(input); }
  catch (e) {
    e.lineNumber = e.line;
    return errorMessage(e, input, templateName);
  }

  try {
    compiled = compiler(parsed);

    _.extend(sandbox, data);
    sandbox.Bluemold = function(i, context, templateName){
      return Bluemold(i, data, templateName);
    };

    return vm.createScript(compiled).runInNewContext(sandbox, "BluemoldTemplate");

  } catch (error) {
    return errorMessage(error, input, templateName, compiled);
  }
}

function errorMessage(e, input, templateName, compiled) {
  e.source   = input;
  e.template = templateName;
  if(e.stack && compiled){
    var stack         = e.stack.split(/\n/ig)[1];
    var errorPosition = (stack.match(/\d+$/) || [0])[0];
    if(errorPosition){
      e.lineNumber = (compiled.substr(0,errorPosition).match(/\\n/ig) || []).length+1;
    }
  }

  return e;
}

exports.Bluemold = Bluemold;
<|endoftext|>


<commit_before>'use strict';

const _ = require( 'lodash' );

const config = require( './config' );

const validation = require( './validation' );

const protect = require( './protect' );

var jwt;		// JWT Validation

var logUncaughtExceptions = true;

function validateJWT( event ) {

	if( jwt ) {

		jwt.validate( event );
	}
}

function validateInput( event ) {

	validation.verify( event );

	protect.scan( event );
}

function isPromise( value ) {

    return ( _.isFunction( value.then ) && _.isFunction( value.catch ) );
}

function wrapHandler( userFunc ) {

	return function( event, context, callback ) {

		try {

			validateJWT( event );

			validateInput( event );

			var retValue = userFunc( event, context, callback );

			if( retValue ) {

                if( isPromise( retValue ) ) {

					retValue
						.then( function( value ) {

                            callback( null, value );
						})
						.catch( function( err ) {

                            callback( err );
						});
				}
				else {

					return retValue;
				}
			}
		}
		catch( err ) {

            if( logUncaughtExceptions ) {

                console.log( '*** vandium - uncaught exception:', err );
            }

            callback( err );
		}
	};
}

function Vandium( userFunc ) {

	return wrapHandler( userFunc )
}

Vandium.validation = function( schema ) {

	if( schema ) {

		validation.configure( schema );
	}

	return validation;
}

Vandium.jwt = function() {

	if( !jwt ) {

		jwt = require( './jwt' );
	}

	return jwt;
}

Vandium.protect = protect;

Vandium.logUncaughtExceptions = function( enable ) {

    logUncaughtExceptions = (enable === true);
}

Object.defineProperty( Vandium, 'types', {

	get: function() {

		return validation.types();
	}
});

config.on( "complete", function() {

	if( config.jwt ) {

		// enable JWT if configured
		Vandium.jwt();
	}
});

module.exports = Vandium;
<commit_msg> Only uncaught exceptions are logged and not those that are raised because of input validation or JWT verification<commit_after>'use strict';

const _ = require( 'lodash' );

const config = require( './config' );

const validation = require( './validation' );

const protect = require( './protect' );

const STAGE_JWT = 10;

const STAGE_INPUT = 20;

const STAGE_EXEC = 30;

var jwt;		// JWT Validation

var logUncaughtExceptions = true;

function validateJWT( event ) {

	if( jwt ) {

		jwt.validate( event );
	}
}

function validateInput( event ) {

	validation.verify( event );

	protect.scan( event );
}

function isPromise( value ) {

    return ( _.isFunction( value.then ) && _.isFunction( value.catch ) );
}

function wrapHandler( userFunc ) {

	return function( event, context, callback ) {

        let stage = 0;

		try {

            stage = STAGE_JWT;
			validateJWT( event );

            stage = STAGE_INPUT;
			validateInput( event );

            stage = STAGE_EXEC;
			var retValue = userFunc( event, context, callback );

			if( retValue ) {

                if( isPromise( retValue ) ) {

					retValue
						.then( function( value ) {

                            callback( null, value );
						})
						.catch( function( err ) {

                            callback( err );
						});
				}
				else {

					return retValue;
				}
			}
		}
		catch( err ) {

            if( logUncaughtExceptions && (stage === STAGE_EXEC) ) {

                console.log( '*** vandium - uncaught exception:', err );
            }

            callback( err );
		}
	};
}

function Vandium( userFunc ) {

	return wrapHandler( userFunc )
}

Vandium.validation = function( schema ) {

	if( schema ) {

		validation.configure( schema );
	}

	return validation;
}

Vandium.jwt = function() {

	if( !jwt ) {

		jwt = require( './jwt' );
	}

	return jwt;
}

Vandium.protect = protect;

Vandium.logUncaughtExceptions = function( enable ) {

    logUncaughtExceptions = (enable === true);
}

Object.defineProperty( Vandium, 'types', {

	get: function() {

		return validation.types();
	}
});

config.on( "complete", function() {

	if( config.jwt ) {

		// enable JWT if configured
		Vandium.jwt();
	}
});

module.exports = Vandium;
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */
var debug = require("debug")("simple-stack-common:middleware:headers");

module.exports = function() {
  return function headerLogger(req, res, next) {
    debug(req.headers);
    next();
  };
};
<commit_msg>Fix header debug output<commit_after>/**
 * Module dependencies
 */
var debug = require("debug")
  , debug.headers = debug("simple-stack-common:middleware:headers"),
  , debug.base = debug("simple-stack-common:middleware:base"),
  , debug.env = debug("simple-stack-common:middleware:env"),
  , debug.body = debug("simple-stack-common:middleware:body");

module.exports = function() {
  return function headerLogger(req, res, next) {
    debug.headers('req.headers\n', req.headers);
    debug.base('req.base\n', req.base);
    debug.env('process.env\n', process.env);
    debug.body('req.body\n', req.body);
    next();
  };
};
<|endoftext|>


<commit_before><commit_msg>made payment complete scrollable<commit_after><|endoftext|>


<commit_before>'use strict';

(function() {

    // Time constants used across the script
    var SECONDS_IN_YEAR = 31536000;
    var SECONDS_IN_WEEK = 604800;
    var SECONDS_IN_DAY = 86400;
    var SECONDS_IN_HOUR = 3600;
    var SECONDS_IN_MINUTE = 60;
    var SECONDS_IN_MILLISECOND = 0.001;
    var MILLISECONDS_IN_SECOND = 1000;
    var ONE_SECOND = 1;

    var TimeSpan = (function TimeSpan() {
        function TimeSpan(seconds) {
            this.val = seconds;
        }

        //Converters
        TimeSpan.prototype.ms = TimeSpan.prototype.milliseconds = function ms() {
            return this.val * MILLISECONDS_IN_SECOND;
        };

        TimeSpan.prototype.seconds = TimeSpan.prototype.second = function seconds() {
            return this.val;
        };

        TimeSpan.prototype.minutes = TimeSpan.prototype.minute = function minutes() {
            return this.val / SECONDS_IN_MINUTE;
        };

        TimeSpan.prototype.hours = TimeSpan.prototype.hour = function hours() {
            return this.val / SECONDS_IN_HOUR;
        };

        TimeSpan.prototype.days = TimeSpan.prototype.day = function days() {
            return this.val / SECONDS_IN_DAY;
        };

        TimeSpan.prototype.weeks = TimeSpan.prototype.day = function weeks() {
            return this.val / SECONDS_IN_WEEK;
        };

        TimeSpan.prototype.years = TimeSpan.prototype.year = function years() {
            return this.val / SECONDS_IN_YEAR;
        };

        //Appenders
        TimeSpan.prototype.addSeconds = function(seconds) {
            this.val += seconds;
            return this;
        };

        TimeSpan.prototype.addMinutes = function(minutes) {
            this.val += minutes * SECONDS_IN_MINUTE;
            return this;
        };

        TimeSpan.prototype.addHours = function(hours) {
            this.val += hours * SECONDS_IN_HOUR;
            return this;
        };

        TimeSpan.prototype.addDays = function(days) {
            this.val += days * SECONDS_IN_DAY;
            return this;
        };

        TimeSpan.prototype.addWeeks = function(weeks) {
            this.val += weeks * SECONDS_IN_WEEK;
            return this;
        };

        TimeSpan.prototype.addYears = function(years) {
            this.val += years * SECONDS_IN_YEAR;
            return this;
        };

        TimeSpan.prototype.addMilliseconds = function(milliseconds) {
            this.val += milliseconds * SECONDS_IN_MILLISECOND;
            return this;
        };

        //Formaters
        TimeSpan.prototype.humanize = function humanize() {
            var val = this.val;

            var transforms = [
                ['Years', SECONDS_IN_YEAR],
                ['Days', SECONDS_IN_DAY],
                ['Hours', SECONDS_IN_HOUR],
                ['Minutes', SECONDS_IN_MINUTE],
                ['Seconds', ONE_SECOND],
                ['Milliseconds', SECONDS_IN_MILLISECOND]
            ];

            /**
             * Function to compute modulo value
             * JS doesn't have a modulo operator built into the language
             * Code taken from this StackOverflow post:
             * http://stackoverflow.com/questions/3966484/floating-point-numbers-and-javascript-modulus-operator
             */
            function floatSafeRemainder(val, step) {
                var valDecCount = (val.toString().split('.')[1] || '').length;
                var stepDecCount = (step.toString().split('.')[1] || '').length;
                var decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
                var valInt = parseInt(val.toFixed(decCount).replace('.', ''));
                var stepInt = parseInt(step.toFixed(decCount).replace('.', ''));

                return (valInt % stepInt) / Math.pow(10, decCount);
            }

            var results = [];
            transforms.forEach(function(t) {
                var div = Math.floor(val / t[1]);
                if (div > 0) {
                    results.push(div + ' ' + t[0]);
                }
                val = floatSafeRemainder(val, t[1]);
            });

            return results.join(', ');
        };

        return TimeSpan;
    }());

    var toTime = (function() {
        function toTime(text) {
            var units = {};
            units.y = units.year = units.years = SECONDS_IN_YEAR;
            units.w = units.week = units.weeks = SECONDS_IN_WEEK;
            units.d = units.day = units.days = SECONDS_IN_DAY;
            units.h = units.hour = units.hours = SECONDS_IN_HOUR;
            units.m = units.minute = units.minutes = SECONDS_IN_MINUTE;
            units.s = units.second = units.seconds = ONE_SECOND;
            units.ms = units.millisecond = units.milliseconds = SECONDS_IN_MILLISECOND;

            var matchPattern = /^[\d]+[\w]+$/;

            var splitted = text.toLowerCase()
                //Replace double whitespaces with single whitespace
                .replace(/\s+/gi, ' ')
                //Remove all commas
                .replace(/[,]/g, '')
                //Used for supporting strings such as '30 Years, 2 Hours'
                .replace(/([\d])\s([\w])/gi, '$1$2')
                //Split array to number-type combinations
                .split(' ');

            var errors = splitted.some(function(v) {
                return v.match(matchPattern) === null;
            });

            if (errors) {
                throw new Error('Invalid format');
            }

            var seconds = splitted
                .filter(function(v) {
                    return v.match(matchPattern);
                })
                .map(function(v) {
                    var numeric = v.match(/[\d]+/)[0];
                    return [parseInt(v.substr(0, numeric.length)), v.substr(numeric.length).toLowerCase()];
                })
                .map(function(v) {
                    return v[0] * units[v[1]];
                })
                .reduce(function(prev, curr) {
                    return prev + curr;
                }, 0);

            if (isNaN(seconds)) {
                throw new Error('Invalid format');
            }

            return new TimeSpan(seconds);
        }

        //Constructors
        toTime.fromMilliseconds = function(milliseconds) {
            return new TimeSpan(milliseconds * SECONDS_IN_MILLISECOND);
        };

        toTime.fromSeconds = function(seconds) {
            return new TimeSpan(seconds);
        };

        toTime.fromMinutes = function(minutes) {
            return new TimeSpan(minutes * SECONDS_IN_MINUTE);
        };

        toTime.fromHours = function(hours) {
            return new TimeSpan(hours * SECONDS_IN_HOUR);
        };

        toTime.fromDays = function(days) {
            return new TimeSpan(days * SECONDS_IN_DAY);
        };

        toTime.fromWeeks = function(weeks) {
            return new TimeSpan(weeks * SECONDS_IN_WEEK);
        };

        toTime.fromYears = function(years) {
            return new TimeSpan(years * SECONDS_IN_YEAR);
        };

        return toTime;
    }());

    // Code below was taken from underscore sourcecode
    // Establish the root object, `window` (`self`) in the browser, `global`
    // on the server, or `this` in some virtual machines. We use `self`
    // instead of `window` for `WebWorker` support.
    var root = typeof self == 'object' && self.self === self && self ||
        typeof global == 'object' && global.global === global && global ||
        this;

    // Export the library for NodeJS, with backward compatability
    // Export code was taken from Underscore sourcecode
    if (typeof exports != 'undefined' && !exports.nodeType) {
        if (typeof module != 'undefined' && !module.nodeType && module.exports) {
            exports = module.exports = toTime;
        }
        exports._ = toTime;
    } else {
        root._ = toTime;
    }

}());<commit_msg>refactor: naming<commit_after>'use strict';

(function() {

    // Time constants used across the script
    var SECONDS_IN_YEAR = 31536000;
    var SECONDS_IN_WEEK = 604800;
    var SECONDS_IN_DAY = 86400;
    var SECONDS_IN_HOUR = 3600;
    var SECONDS_IN_MINUTE = 60;
    var SECONDS_IN_MILLISECOND = 0.001;
    var MILLISECONDS_IN_SECOND = 1000;
    var ONE_SECOND = 1;

    var TimeFrame = (function TimeFrame() {
        function TimeFrame(seconds) {
            this.val = seconds;
        }

        //Converters
        TimeFrame.prototype.ms = TimeFrame.prototype.milliseconds = function ms() {
            return this.val * MILLISECONDS_IN_SECOND;
        };

        TimeFrame.prototype.seconds = TimeFrame.prototype.second = function seconds() {
            return this.val;
        };

        TimeFrame.prototype.minutes = TimeFrame.prototype.minute = function minutes() {
            return this.val / SECONDS_IN_MINUTE;
        };

        TimeFrame.prototype.hours = TimeFrame.prototype.hour = function hours() {
            return this.val / SECONDS_IN_HOUR;
        };

        TimeFrame.prototype.days = TimeFrame.prototype.day = function days() {
            return this.val / SECONDS_IN_DAY;
        };

        TimeFrame.prototype.weeks = TimeFrame.prototype.day = function weeks() {
            return this.val / SECONDS_IN_WEEK;
        };

        TimeFrame.prototype.years = TimeFrame.prototype.year = function years() {
            return this.val / SECONDS_IN_YEAR;
        };

        //Appenders
        TimeFrame.prototype.addSeconds = function(seconds) {
            this.val += seconds;
            return this;
        };

        TimeFrame.prototype.addMinutes = function(minutes) {
            this.val += minutes * SECONDS_IN_MINUTE;
            return this;
        };

        TimeFrame.prototype.addHours = function(hours) {
            this.val += hours * SECONDS_IN_HOUR;
            return this;
        };

        TimeFrame.prototype.addDays = function(days) {
            this.val += days * SECONDS_IN_DAY;
            return this;
        };

        TimeFrame.prototype.addWeeks = function(weeks) {
            this.val += weeks * SECONDS_IN_WEEK;
            return this;
        };

        TimeFrame.prototype.addYears = function(years) {
            this.val += years * SECONDS_IN_YEAR;
            return this;
        };

        TimeFrame.prototype.addMilliseconds = function(milliseconds) {
            this.val += milliseconds * SECONDS_IN_MILLISECOND;
            return this;
        };

        //Formaters
        TimeFrame.prototype.humanize = function humanize() {
            var val = this.val;

            var transforms = [
                ['Years', SECONDS_IN_YEAR],
                ['Days', SECONDS_IN_DAY],
                ['Hours', SECONDS_IN_HOUR],
                ['Minutes', SECONDS_IN_MINUTE],
                ['Seconds', ONE_SECOND],
                ['Milliseconds', SECONDS_IN_MILLISECOND]
            ];

            /**
             * Function to compute modulo value
             * JS doesn't have a modulo operator built into the language
             * Code taken from this StackOverflow post:
             * http://stackoverflow.com/questions/3966484/floating-point-numbers-and-javascript-modulus-operator
             */
            function floatSafeRemainder(val, step) {
                var valDecCount = (val.toString().split('.')[1] || '').length;
                var stepDecCount = (step.toString().split('.')[1] || '').length;
                var decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
                var valInt = parseInt(val.toFixed(decCount).replace('.', ''));
                var stepInt = parseInt(step.toFixed(decCount).replace('.', ''));

                return (valInt % stepInt) / Math.pow(10, decCount);
            }

            var results = [];
            transforms.forEach(function(t) {
                var div = Math.floor(val / t[1]);
                if (div > 0) {
                    results.push(div + ' ' + t[0]);
                }
                val = floatSafeRemainder(val, t[1]);
            });

            return results.join(', ');
        };

        return TimeFrame;
    }());

    var toTime = (function() {
        function toTime(text) {
            var units = {};
            units.y = units.year = units.years = SECONDS_IN_YEAR;
            units.w = units.week = units.weeks = SECONDS_IN_WEEK;
            units.d = units.day = units.days = SECONDS_IN_DAY;
            units.h = units.hour = units.hours = SECONDS_IN_HOUR;
            units.m = units.minute = units.minutes = SECONDS_IN_MINUTE;
            units.s = units.second = units.seconds = ONE_SECOND;
            units.ms = units.millisecond = units.milliseconds = SECONDS_IN_MILLISECOND;

            var matchPattern = /^[\d]+[\w]+$/;

            var splitted = text.toLowerCase()
                //Replace double whitespaces with single whitespace
                .replace(/\s+/gi, ' ')
                //Remove all commas
                .replace(/[,]/g, '')
                //Used for supporting strings such as '30 Years, 2 Hours'
                .replace(/([\d])\s([\w])/gi, '$1$2')
                //Split array to number-type combinations
                .split(' ');

            var errors = splitted.some(function(v) {
                return v.match(matchPattern) === null;
            });

            if (errors) {
                throw new Error('Invalid format');
            }

            var seconds = splitted
                .filter(function(v) {
                    return v.match(matchPattern);
                })
                .map(function(v) {
                    var numeric = v.match(/[\d]+/)[0];
                    return [parseInt(v.substr(0, numeric.length)), v.substr(numeric.length).toLowerCase()];
                })
                .map(function(v) {
                    return v[0] * units[v[1]];
                })
                .reduce(function(prev, curr) {
                    return prev + curr;
                }, 0);

            if (isNaN(seconds)) {
                throw new Error('Invalid format');
            }

            return new TimeFrame(seconds);
        }

        //Constructors
        toTime.fromMilliseconds = function(milliseconds) {
            return new TimeFrame(milliseconds * SECONDS_IN_MILLISECOND);
        };

        toTime.fromSeconds = function(seconds) {
            return new TimeFrame(seconds);
        };

        toTime.fromMinutes = function(minutes) {
            return new TimeFrame(minutes * SECONDS_IN_MINUTE);
        };

        toTime.fromHours = function(hours) {
            return new TimeFrame(hours * SECONDS_IN_HOUR);
        };

        toTime.fromDays = function(days) {
            return new TimeFrame(days * SECONDS_IN_DAY);
        };

        toTime.fromWeeks = function(weeks) {
            return new TimeFrame(weeks * SECONDS_IN_WEEK);
        };

        toTime.fromYears = function(years) {
            return new TimeFrame(years * SECONDS_IN_YEAR);
        };

        return toTime;
    }());

    // Code below was taken from underscore sourcecode
    // Establish the root object, `window` (`self`) in the browser, `global`
    // on the server, or `this` in some virtual machines. We use `self`
    // instead of `window` for `WebWorker` support.
    var root = typeof self == 'object' && self.self === self && self ||
        typeof global == 'object' && global.global === global && global ||
        this;

    // Export the library for NodeJS, with backward compatability
    // Export code was taken from Underscore sourcecode
    if (typeof exports != 'undefined' && !exports.nodeType) {
        if (typeof module != 'undefined' && !module.nodeType && module.exports) {
            exports = module.exports = toTime;
        }
        exports._ = toTime;
    } else {
        root._ = toTime;
    }

}());<|endoftext|>


<commit_before>'use strict';

var BabyParse = require('babyparse');

module.exports = {
  generateLanguageObject : generateLanguageObject,
  i18nScript : i18nScript
};

function parseMarkdown(str)
{
  return str.replace(/\*\*([^\*]+)\*\*/,'$1') //bold
            .replace(/\*([^\*]+)\*/,'$1') //italy
            .replace(/\n/,'
') //enter
            .replace(/\[([^\]]+)\]\(([^\)]+)\)/,'$1') //link
}

function generateLanguageObject(csv)
{
  var json = BabyParse.parse(csv).data;
  var languages = {};
  var headers = [];

  json[0].forEach(function(header, i)
  {
    if(i == 0 || !header.trim())
    {
      return;
    }

    languages[header] = {};
    headers.push(header);
  });

  for(var i = 1; i < json.length; i++)
  {
    if(!json[i][0].trim())
    {
      continue;
    }

    for(var j = 0; j < headers.length; j++)
    {
      languages[headers[j]][json[i][0]] = parseMarkdown(json[i][j + 1]);
    }
  }

  return languages;
}

function i18nScript(lang)
{
  var imported = document.createElement('script');
  var fileImport = 'angular-locale_' + lang.toLowerCase().replace(/_/g, '-') + '.js';
  imported.src = 'https://code.angularjs.org/1.2.10/i18n/' + fileImport;
  imported.onload = function()
  {
    document.head.removeChild(imported);
  };
  document.head.appendChild(imported);
}
<commit_msg>added global parse to the markdown<commit_after>'use strict';

var BabyParse = require('babyparse');

module.exports = {
  generateLanguageObject : generateLanguageObject,
  i18nScript : i18nScript
};

function parseMarkdown(str)
{
  return str.replace(/\*\*([^\*]+)\*\*/g,'$1') //bold
            .replace(/\*([^\*]+)\*/g,'$1') //italy
            .replace(/\n/g,'
') //enter
            .replace(/\[([^\]]+)\]\(([^\)]+)\)/g,'$1') //link
}

function generateLanguageObject(csv)
{
  var json = BabyParse.parse(csv).data;
  var languages = {};
  var headers = [];

  json[0].forEach(function(header, i)
  {
    if(i == 0 || !header.trim())
    {
      return;
    }

    languages[header] = {};
    headers.push(header);
  });

  for(var i = 1; i < json.length; i++)
  {
    if(!json[i][0].trim())
    {
      continue;
    }

    for(var j = 0; j < headers.length; j++)
    {
      languages[headers[j]][json[i][0]] = parseMarkdown(json[i][j + 1]);
    }
  }

  return languages;
}

function i18nScript(lang)
{
  var imported = document.createElement('script');
  var fileImport = 'angular-locale_' + lang.toLowerCase().replace(/_/g, '-') + '.js';
  imported.src = 'https://code.angularjs.org/1.2.10/i18n/' + fileImport;
  imported.onload = function()
  {
    document.head.removeChild(imported);
  };
  document.head.appendChild(imported);
}
<|endoftext|>


<commit_before>// Batch Request

var _ = require('lodash'),
    check = require('validator').check,
    methods = require('methods'),
    Promise = require('bluebird'),
    request = Promise.promisify(require('request')),
    url = require('url'),
    template = require('es6-template-strings');

function getFinalUrl(req, r) {
    // Accept either uri or url (this is what request does, we just mirror)
    r.url = r.url || r.uri;

    // Convert relative paths to full paths
    if (typeof r.url === 'string' && /^\//.test(r.url) === true) {
        return req.protocol + '://' + req.get('host') + r.url;
    }

    return r.url;
}

var batchRequest = function(params) {

    // Set default option values
    params = params || {};
    params.localOnly = (typeof params.localOnly === 'undefined') ? true : params.localOnly;
    params.httpsAlways = (typeof params.localOnly === 'undefined') ? false : params.localOnly;
    params.max = (typeof params.max === 'undefined') ? 20 : params.max;
    params.validateRespond = (typeof params.validateRespond === 'undefined') ? true : params.validateRespond;
    params.allowedHosts = (typeof params.allowedHosts === 'undefined') ? null : params.allowedHosts;
    params.defaultHeaders = (typeof params.defaultHeaders === 'undefined') ? {} : params.defaultHeaders;
    params.forwardHeaders = (typeof params.forwardHeaders === 'undefined') ? [] : params.forwardHeaders;

    var batch = function(req, res, next) {
        // Here we assume it the request has already been validated, either by
        // our included middleware or otherwise by the app developer.

        // We also assume it has been run through some middleware like
        // express.bodyParser() or express.json() to parse the requests

        var requests = req.body;

        var requestPromise = function(r) {
            r.headers = r.headers || {};

            r.url = getFinalUrl(req, r);

            _.each(params.defaultHeaders, function(headerV, headerK) {
                if (!(headerK in r.headers)) { // copy defaults if not already exposed
                    r.headers[headerK] = headerV;
                }
            });
            _.each(params.forwardHeaders, function(headerK) {
                if (!(headerK in r.headers) && headerK in req.headers) { // copy forward if not already exposed
                    var forwardValue = req.headers[headerK];
                    r.headers[headerK] = forwardValue;
                }
            });
            return request(r).spread(function(response, body) {
                if ( response.headers['content-type'].indexOf( 'application/json' ) > -1 ) {
                    body = JSON.parse( body );
                }
                return {
                    'statusCode': response.statusCode,
                    'body': body,
                    'headers': response.headers
                };
            });
        };

        // First, let's fire off all calls without any dependencies, accumulate their promises
        var requestPromises = _.reduce(requests, function(promises, r, key) {
            if (!r.dependency || r.dependency === 'none') {
                promises[key] = requestPromise(r);
            }
            // And while we do that, build the dependency object with those items as keys
            // { key: Promise }
            return promises;
        }, {});

        // Then recursively iterate over all items with dependencies, resolving some at each pass
        var recurseDependencies = function (reqs) {

            // console.log( reqs );
            console.log( requestPromises );

            // End state hit when the number of promises we have matches the number
            // of request objects we started with.
            if (_.size(requestPromises) >= _.size(reqs)) {
                return;
            } else {
                _.each(requestPromises, function(rp, key) {
                    console.log( rp );
                    console.log( key );
                    var dependentKey = null;
                    var dependent = _.find(reqs, function(request, dKey) {
                        dependentKey = dKey;
                        return request.dependency === key && (typeof requestPromises[dKey] === 'undefined');
                    });
                    if (dependent) {
                        requestPromises[dependentKey] = rp.then(function( dependencyResponse ) {
                            console.log( dependencyResponse ); // This has the JSON response from the dependency
                            console.log( dependent ); // This has the JSON request from the dependent

                            // var jsonRequest = JSON.stringify( dependent );
                            // jsonRequest = template( jsonRequest, { dependency: dependencyResponse } );
                            // dependent = JSON.parse( jsonRequest );

                            var templateableFields = {
                                form: [
                                    'html', 'subject'
                                ]
                            };

                            // This would be better served by an intelligent (distinguish array from object) recursive function
                            _.each( templateableFields, function( fieldsArray, key ) {
                                _.each( fieldsArray, function( field, index ) {
                                    dependent[ key ][ field ] = template( dependent[ key ][ field ], { dependency: dependencyResponse } );
                                });
                            });

                            console.log( dependent );

                            // dependent.form.html = template( dependent.form.html, { dependency: dependencyResponse } );
                            return requestPromise(dependent);
                        });
                    }
                });
                recurseDependencies(reqs);
            }
        };

        // Recurse dependencies
        recurseDependencies(requests);

        // Wait for all to complete before responding
        Promise.props(requestPromises).then(function(result) {

            // remove all properties, except status, body, and headers
            var output = {};
            for(var prop in result){
                output[prop] = { statusCode: result[prop].statusCode, body: result[prop].body, headers: result[prop].headers};
            }
            res.json(output);
            // next(); // this line is causing the response to be 0
        });
    };

    batch.validate = function(req, res, next) {
        var err = null,
            requests = req.body,
            requestHost;

        // Validation on Request object as a whole
        try {
            check(_.size(requests), 'Cannot make a batch request with an empty request object').min(1);
            check(_.size(requests), 'Over the max request limit. Please limit batches to ' + params.max + ' requests').max(params.max);
            if (req.method === 'POST' && !req.is('json')) {
                throw new Error('Batch Request will only accept body as json');
            }
        } catch (e) {
            err = {
                error: {
                    'message': e.message,
                    'type': 'ValidationError'
                }
            };
        }

        // Validation on each request object
        _.each(requests, function(r, key) {

            // If no method provided, default to GET
            r.method = (typeof r.method === 'string') ? r.method.toLowerCase() : 'get';

            r.url = getFinalUrl(req, r);

            try {
                check(r.url, 'Invalid URL').isUrl();
                check(r.method, 'Invalid method').isIn(methods);
                if (r.body !== undefined) {
                    check(r.method.toLowerCase(), 'Request body not allowed for this method').isIn(['put', 'post', 'options']);
                }
            } catch (e) {
                err = {
                    error: {
                        'message': e.message,
                        'request': key,
                        'type': 'ValidationError'
                    }
                };
            }

            if (params.allowedHosts !== null) {
                requestHost = url.parse(r.url).host;
                if (params.allowedHosts.indexOf(requestHost) === -1) {
                    err = {
                        error: {
                            'message': 'Cannot make batch request to a host which is not allowed',
                            'host': requestHost,
                            'type': 'ValidationError'
                        }
                    };
                }
            }
        });

        if (err !== null) {
            res.status(400).send(err);
            next(err);
        } else {
            next();
        }
    };

    return batch;
};

module.exports = batchRequest;
<commit_msg>Parsing entire request as a JSON string for es6 template instead of on a field-by-field basis.<commit_after>// Batch Request

var _ = require('lodash'),
    check = require('validator').check,
    methods = require('methods'),
    Promise = require('bluebird'),
    request = Promise.promisify(require('request')),
    url = require('url'),
    template = require('es6-template-strings');

function getFinalUrl(req, r) {
    // Accept either uri or url (this is what request does, we just mirror)
    r.url = r.url || r.uri;

    // Convert relative paths to full paths
    if (typeof r.url === 'string' && /^\//.test(r.url) === true) {
        return req.protocol + '://' + req.get('host') + r.url;
    }

    return r.url;
}

var batchRequest = function(params) {

    // Set default option values
    params = params || {};
    params.localOnly = (typeof params.localOnly === 'undefined') ? true : params.localOnly;
    params.httpsAlways = (typeof params.localOnly === 'undefined') ? false : params.localOnly;
    params.max = (typeof params.max === 'undefined') ? 20 : params.max;
    params.validateRespond = (typeof params.validateRespond === 'undefined') ? true : params.validateRespond;
    params.allowedHosts = (typeof params.allowedHosts === 'undefined') ? null : params.allowedHosts;
    params.defaultHeaders = (typeof params.defaultHeaders === 'undefined') ? {} : params.defaultHeaders;
    params.forwardHeaders = (typeof params.forwardHeaders === 'undefined') ? [] : params.forwardHeaders;

    var batch = function(req, res, next) {
        // Here we assume it the request has already been validated, either by
        // our included middleware or otherwise by the app developer.

        // We also assume it has been run through some middleware like
        // express.bodyParser() or express.json() to parse the requests

        var requests = req.body;

        var requestPromise = function(r) {
            r.headers = r.headers || {};

            r.url = getFinalUrl(req, r);

            _.each(params.defaultHeaders, function(headerV, headerK) {
                if (!(headerK in r.headers)) { // copy defaults if not already exposed
                    r.headers[headerK] = headerV;
                }
            });
            _.each(params.forwardHeaders, function(headerK) {
                if (!(headerK in r.headers) && headerK in req.headers) { // copy forward if not already exposed
                    var forwardValue = req.headers[headerK];
                    r.headers[headerK] = forwardValue;
                }
            });
            return request(r).spread(function(response, body) {
                if ( response.headers['content-type'].indexOf( 'application/json' ) > -1 ) {
                    body = JSON.parse( body );
                }
                return {
                    'statusCode': response.statusCode,
                    'body': body,
                    'headers': response.headers
                };
            });
        };

        // First, let's fire off all calls without any dependencies, accumulate their promises
        var requestPromises = _.reduce(requests, function(promises, r, key) {
            if (!r.dependency || r.dependency === 'none') {
                promises[key] = requestPromise(r);
            }
            // And while we do that, build the dependency object with those items as keys
            // { key: Promise }
            return promises;
        }, {});

        // Then recursively iterate over all items with dependencies, resolving some at each pass
        var recurseDependencies = function (reqs) {

            // console.log( reqs );
            console.log( requestPromises );

            // End state hit when the number of promises we have matches the number
            // of request objects we started with.
            if (_.size(requestPromises) >= _.size(reqs)) {
                return;
            } else {
                _.each(requestPromises, function(rp, key) {
                    console.log( rp );
                    console.log( key );
                    var dependentKey = null;
                    var dependent = _.find(reqs, function(request, dKey) {
                        dependentKey = dKey;
                        return request.dependency === key && (typeof requestPromises[dKey] === 'undefined');
                    });
                    if (dependent) {
                        requestPromises[dependentKey] = rp.then(function( dependencyResponse ) {
                            console.log( dependencyResponse ); // This has the JSON response from the dependency
                            console.log( dependent ); // This has the JSON request from the dependent

                            var jsonRequest = JSON.stringify( dependent );
                            jsonRequest = template( jsonRequest, { dependency: dependencyResponse } );
                            dependent = JSON.parse( jsonRequest );

                            console.log( dependent );

                            // dependent.form.html = template( dependent.form.html, { dependency: dependencyResponse } );
                            return requestPromise(dependent);
                        });
                    }
                });
                recurseDependencies(reqs);
            }
        };

        // Recurse dependencies
        recurseDependencies(requests);

        // Wait for all to complete before responding
        Promise.props(requestPromises).then(function(result) {

            // remove all properties, except status, body, and headers
            var output = {};
            for(var prop in result){
                output[prop] = { statusCode: result[prop].statusCode, body: result[prop].body, headers: result[prop].headers};
            }
            res.json(output);
            // next(); // this line is causing the response to be 0
        });
    };

    batch.validate = function(req, res, next) {
        var err = null,
            requests = req.body,
            requestHost;

        // Validation on Request object as a whole
        try {
            check(_.size(requests), 'Cannot make a batch request with an empty request object').min(1);
            check(_.size(requests), 'Over the max request limit. Please limit batches to ' + params.max + ' requests').max(params.max);
            if (req.method === 'POST' && !req.is('json')) {
                throw new Error('Batch Request will only accept body as json');
            }
        } catch (e) {
            err = {
                error: {
                    'message': e.message,
                    'type': 'ValidationError'
                }
            };
        }

        // Validation on each request object
        _.each(requests, function(r, key) {

            // If no method provided, default to GET
            r.method = (typeof r.method === 'string') ? r.method.toLowerCase() : 'get';

            r.url = getFinalUrl(req, r);

            try {
                check(r.url, 'Invalid URL').isUrl();
                check(r.method, 'Invalid method').isIn(methods);
                if (r.body !== undefined) {
                    check(r.method.toLowerCase(), 'Request body not allowed for this method').isIn(['put', 'post', 'options']);
                }
            } catch (e) {
                err = {
                    error: {
                        'message': e.message,
                        'request': key,
                        'type': 'ValidationError'
                    }
                };
            }

            if (params.allowedHosts !== null) {
                requestHost = url.parse(r.url).host;
                if (params.allowedHosts.indexOf(requestHost) === -1) {
                    err = {
                        error: {
                            'message': 'Cannot make batch request to a host which is not allowed',
                            'host': requestHost,
                            'type': 'ValidationError'
                        }
                    };
                }
            }
        });

        if (err !== null) {
            res.status(400).send(err);
            next(err);
        } else {
            next();
        }
    };

    return batch;
};

module.exports = batchRequest;
<|endoftext|>


<commit_before>'use strict';

function Encoder() {
  this.buffer_ = [];
  this.bitIndex_ = 0;
}

Encoder.prototype.encodeOctet = function(o) {
  this.buffer_.push(o & 0xff);
};

Encoder.prototype.encodeInteger = function(firstOctetMask, N, I) {
  var nextMarker = (1 << N) - 1;

  if (I < nextMarker) {
    this.encodeOctet(firstOctetMask | I);
    return;
  }

  if (N > 0) {
    this.encodeOctet(firstOctetMask | nextMarker);
  }

  I -= nextMarker;
  while (I >= 128) {
    this.encodeOctet(I % 128 | 128);
    I /= 128;
  }
  this.encodeOctet(I);
}

Encoder.prototype.encodeASCIIString = function(str) {
  this.encodeInteger(0, 0, str.length);
  for (var i = 0; i < str.length; ++i) {
    this.encodeOctet(str.charCodeAt(i));
  }
}

Encoder.prototype.encodeIndexedHeader = function(index) {
  var opCode = 0x80;
  var prefixLength = 7;
  this.encodeInteger(opCode, prefixLength, index);
}

Encoder.prototype.encodeLiteralHeaderWithoutIndexing = function(
  indexOrName, value) {
  var opCode = 0x60;
  var prefixLength = 5;
  switch (typeof indexOrName) {
    case 'number':
      this.encodeInteger(opCode, prefixLength, indexOrName + 1);
      this.encodeASCIIString(value);
      return;

    case 'string':
      this.encodeInteger(opCode, prefixLength, 0);
      this.encodeASCIIString(indexOrName);
      this.encodeASCIIString(value);
      return;
  }

  throw new Error('not an index or name: ' + indexOrName);
}

Encoder.prototype.encodeLiteralHeaderWithIncrementalIndexing = function(
  indexOrName, value) {
  var opCode = 0x20;
  var prefixLength = 5;
  switch (typeof indexOrName) {
    case 'number':
      this.encodeInteger(opCode, prefixLength, indexOrName + 1);
      this.encodeASCIIString(value);
      return;

    case 'string':
      this.encodeInteger(opCode, prefixLength, 0);
      this.encodeASCIIString(indexOrName);
      this.encodeASCIIString(value);
      return;
  }

  throw new Error('not an index or name: ' + indexOrName);
}

Encoder.prototype.encodeLiteralHeaderWithSubstitutionIndexing = function(
  indexOrName, substitutedIndex, value) {
  var opCode = 0x0;
  var prefixLength = 6;
  switch (typeof indexOrName) {
    case 'number':
      this.encodeInteger(opCode, prefixLength, indexOrName + 1);
      this.encodeInteger(0, 0, substitutedIndex);
      this.encodeASCIIString(value);
      return;

    case 'string':
      this.encodeInteger(opCode, prefixLength, 0);
      this.encodeASCIIString(indexOrName);
      this.encodeInteger(0, 0, substitutedIndex);
      this.encodeASCIIString(value);
      return;
  }

  throw new Error('not an index or name: ' + indexOrName);
}

function HeaderTable() {
  this.entries_ = [];
  this.size_ = 0;
  this.maxSize_ = 4096;
}

HeaderTable.prototype.removeFirstEntry_ = function() {
  var firstEntry = this.entries_.shift();
  this.size_ -= firstEntry.name.length + firstEntry.value.length + 32;
}

HeaderTable.prototype.tryAppendEntry = function(name, value) {
  var sizeDelta = name.length + value.length + 32;
  while (this.entries_.length > 0 && this.size_ + sizeDelta > this.maxSize_) {
    this.removeFirstEntry_();
  }
  if (this.size_ + sizeDelta <= this.maxSize_) {
    this.size_ += sizeDelta;
    this.entries_.push({ name: name, value: value });
  }
}
<commit_msg>Implement HeaderTable.tryReplaceEntry()<commit_after>'use strict';

function Encoder() {
  this.buffer_ = [];
  this.bitIndex_ = 0;
}

Encoder.prototype.encodeOctet = function(o) {
  this.buffer_.push(o & 0xff);
};

Encoder.prototype.encodeInteger = function(firstOctetMask, N, I) {
  var nextMarker = (1 << N) - 1;

  if (I < nextMarker) {
    this.encodeOctet(firstOctetMask | I);
    return;
  }

  if (N > 0) {
    this.encodeOctet(firstOctetMask | nextMarker);
  }

  I -= nextMarker;
  while (I >= 128) {
    this.encodeOctet(I % 128 | 128);
    I /= 128;
  }
  this.encodeOctet(I);
}

Encoder.prototype.encodeASCIIString = function(str) {
  this.encodeInteger(0, 0, str.length);
  for (var i = 0; i < str.length; ++i) {
    this.encodeOctet(str.charCodeAt(i));
  }
}

Encoder.prototype.encodeIndexedHeader = function(index) {
  var opCode = 0x80;
  var prefixLength = 7;
  this.encodeInteger(opCode, prefixLength, index);
}

Encoder.prototype.encodeLiteralHeaderWithoutIndexing = function(
  indexOrName, value) {
  var opCode = 0x60;
  var prefixLength = 5;
  switch (typeof indexOrName) {
    case 'number':
      this.encodeInteger(opCode, prefixLength, indexOrName + 1);
      this.encodeASCIIString(value);
      return;

    case 'string':
      this.encodeInteger(opCode, prefixLength, 0);
      this.encodeASCIIString(indexOrName);
      this.encodeASCIIString(value);
      return;
  }

  throw new Error('not an index or name: ' + indexOrName);
}

Encoder.prototype.encodeLiteralHeaderWithIncrementalIndexing = function(
  indexOrName, value) {
  var opCode = 0x20;
  var prefixLength = 5;
  switch (typeof indexOrName) {
    case 'number':
      this.encodeInteger(opCode, prefixLength, indexOrName + 1);
      this.encodeASCIIString(value);
      return;

    case 'string':
      this.encodeInteger(opCode, prefixLength, 0);
      this.encodeASCIIString(indexOrName);
      this.encodeASCIIString(value);
      return;
  }

  throw new Error('not an index or name: ' + indexOrName);
}

Encoder.prototype.encodeLiteralHeaderWithSubstitutionIndexing = function(
  indexOrName, substitutedIndex, value) {
  var opCode = 0x0;
  var prefixLength = 6;
  switch (typeof indexOrName) {
    case 'number':
      this.encodeInteger(opCode, prefixLength, indexOrName + 1);
      this.encodeInteger(0, 0, substitutedIndex);
      this.encodeASCIIString(value);
      return;

    case 'string':
      this.encodeInteger(opCode, prefixLength, 0);
      this.encodeASCIIString(indexOrName);
      this.encodeInteger(0, 0, substitutedIndex);
      this.encodeASCIIString(value);
      return;
  }

  throw new Error('not an index or name: ' + indexOrName);
}

function HeaderTable() {
  this.entries_ = [];
  this.size_ = 0;
  this.maxSize_ = 4096;
}

HeaderTable.prototype.removeFirstEntry_ = function() {
  var firstEntry = this.entries_.shift();
  this.size_ -= firstEntry.name.length + firstEntry.value.length + 32;
}

HeaderTable.prototype.tryAppendEntry = function(name, value) {
  var sizeDelta = name.length + value.length + 32;
  while (this.entries_.length > 0 && this.size_ + sizeDelta > this.maxSize_) {
    this.removeFirstEntry_();
  }
  if (this.size_ + sizeDelta <= this.maxSize_) {
    this.size_ += sizeDelta;
    this.entries_.push({ name: name, value: value });
  }
}

HeaderTable.prototype.tryReplaceEntry = function(index, name, value) {
  var existingEntry = this.entries_[index];
  var sizeDelta =
    (name.length + value.length + 32) -
    (existingEntry.name.length + existingEntry.value.length + 32);
  while (this.entries_.length > 0 && this.size_ + sizeDelta > this.maxSize_) {
    --index;
    this.removeFirstEntry_();
  }
  if (this.size_ + sizeDelta <= this.maxSize_) {
    this.size_ += sizeDelta;
    var newEntry = { name: name, value: value };
    if (index >= 0) {
      this.entries_[index] = newEntry;
    } else {
      this.entries_.unshift(newEntry);
    }
  }
}
<|endoftext|>


<commit_before>/* @flow */
'use strict';

function getFileFromKey (
  bucketPathPrefix /* : string */,
  key /* : string */
) {
  let file = key;
  if (bucketPathPrefix) {
    // bucketPathPrefix.length - 1 as it will end '/'
    file = file.substr(bucketPathPrefix.length);
  }
  return file;
}

function validate (
  bucketPathPrefix /* : string | void */
) /* : string */ {
  if (!bucketPathPrefix) {
    return '';
  }

  // prefix should have a slack at the end or be an empty string.
  if (!bucketPathPrefix.endsWith('/')) {
    bucketPathPrefix += '/';
  }

  // If str starts with a slash, remove it and start validation again.
  if (bucketPathPrefix.startsWith('/')) {
    return validate(bucketPathPrefix.substr(1));
  }

  return bucketPathPrefix;
}

module.exports = {
  getFileFromKey,
  validate
};
<commit_msg>CC-32 # Fixed typo in comment<commit_after>/* @flow */
'use strict';

function getFileFromKey (
  bucketPathPrefix /* : string */,
  key /* : string */
) {
  let file = key;
  if (bucketPathPrefix) {
    // bucketPathPrefix.length - 1 as it will end '/'
    file = file.substr(bucketPathPrefix.length);
  }
  return file;
}

function validate (
  bucketPathPrefix /* : string | void */
) /* : string */ {
  if (!bucketPathPrefix) {
    return '';
  }

  // prefix should have a slash at the end or be an empty string.
  if (!bucketPathPrefix.endsWith('/')) {
    bucketPathPrefix += '/';
  }

  // If str starts with a slash, remove it and start validation again.
  if (bucketPathPrefix.startsWith('/')) {
    return validate(bucketPathPrefix.substr(1));
  }

  return bucketPathPrefix;
}

module.exports = {
  getFileFromKey,
  validate
};
<|endoftext|>


<commit_before>/*global console process require setInterval*/

// Imports and globals.
var http = require("http"),
    url = require("url"),
    net = require("net"),
    log4js = require('log4js-node'),
    dgram = require("dgram"),
    osc = require("./libs/osc.js"),
    netIP = require("./libs/netIP.js"),
    ac = require("./client.js"),
    msg = require("./msg.js"),
    querystring = require("querystring");

var DEBUG = 1,
    INTERNAL_IP = "",
    OSC_PORT = 9090,
    WS_PORT = 9091,
    HTTP_PORT = 9092,
    TCP_PORT = 9093,
    TIMEOUT = 600000; // Seconds before kicking idle clients.

// The list of clients
var clients = new ac.AcequiaClients(TIMEOUT * 1000);

var oscServer, wsServer;

var logger = log4js.getLogger("acequia");

// Message routing goes here.
function onMessage(from, to, title, body, tt) {
    if (to) {
        clients.sendTo(to, from, title, body, tt);
    } else {
        clients.broadcast(from, title, body, tt);
    }
}

// Kicks any clients who we have not heard from for a while.
function kickIdle() {
    clients.clearExpired();
}

// Once we actually get our internal IP, we start the servers.
function startServers() {
    var i, from, to, title, tt, client, portOut,
    request, clientList;

    //OSC Server.
    oscServer = dgram.createSocket("udp4");

    oscServer.on("message", function (msg, rinfo) {
        var cli, oscMsgs = osc.bufferToOsc(msg),  oscMsg, i;

        for (i in oscMsgs) {
            oscMsg = oscMsgs[i];
            logger.debug(JSON.stringify(oscMsg));
            switch (oscMsg.address) {
            case msg.MSG_CONNECT:
                // TODO:  How do you send a reject message if the user already exists?
                //the second parameter when logging in is an optional "port to send to".
                portOut = (oscMsg.data[1] > 0) ? oscMsg.data[1] : rinfo.port;
                client = new ac.OSCClient(oscMsg.data[0], rinfo.address, rinfo.port, portOut, oscServer);
                clients.add(client);
                logger.debug("Added client " + oscMsg.data[0] +
                      " (OSC@" + rinfo.address + ":" + rinfo.port + ", client #" + (clients.length - 1) + ")");
                break;

            case msg.MSG_DISCONNECT:
                cli = clients.find(ac.TYP_OSC, rinfo.address, rinfo.por);
                if (cli) {
                    clients.remove(cli.name, "disconnect by user");
                }
                break;

            default:
                from = ""; // clients.find(ac.TYP_OSC, rinfo.address, rinfo.port).name;
                to = ""; // clients.get(oscMsg.data.shift()).name;
                title = oscMsg.address;
                tt = oscMsg.typeTags.slice(1);
                onMessage(from, to, title, oscMsg.data, tt);
                break;
            }
        }
    });

    // This is the bit of code that tells plasticSarcastic what ip and port we are.
    // Essentially our authentication/auto-discovery method for right now.
    oscServer.on("listening", function () {
        logger.debug("oscServer is listening on " + oscServer.address().address + ":" + oscServer.address().port);
    });

    oscServer.on("close", function () {
        logger.debug("oscServer closed");
    });

    oscServer.bind(OSC_PORT, INTERNAL_IP);

    // Websocket server:
    wsServer = require('socket.io').listen(WS_PORT);

//    wsServer.enable('browser client minification');  // send minified client
    wsServer.enable('browser client etag');          // apply etag caching logic based on version number
    wsServer.enable('browser client gzip');          // gzip the file
    wsServer.set('log level', 1);                    // reduce logging
    wsServer.set('transports', [                     // enable all transports (optional if you want flashsocket)
        'websocket',
        'flashsocket',
        'htmlfile',
        'xhr-polling',
        'jsonp-polling'
    ]);

    wsServer.sockets.on('connection', function (socket) {

        logger.debug(socket.id + " Connected");
        socket.on('message', function (data) {
            logger.debug(this.id + " Received message: " + data);

            var message = JSON.parse(data);

            switch (message.name) {
            case msg.MSG_CONNECT:
                client = new ac.WebSocketClient(message.from, this.id, socket);
                try {
                    clients.add(client);
                } catch (e) {
                    var m = new msg.AcequiaMessage("SYS", msg.MSG_CONNECT, -1);
                    wsServer.emit(m.toString());
                }
                client.send("SYS", msg.MSG_CONNECT, 1);
                break;

            case msg.MSG_DISCONNECT:
                clients.get(message.from).send("SYS", msg.MSG_DISCONNECT, 1);
                clients.remove(message.from, "disconnect by user.");
                break;

            case msg.MSG_GETCLIENTS:
                var clientList = [], cli;
                for (cli in clients.clients) {
                    clientList.push(clients.clients[cli].name);
                }
                clients.get(message.from).send("SYS", msg.MSG_GETCLIENTS, clientList);
                break;

            default:
                onMessage(message.from, message.to, message.name, message.body);
                break;
            }
        });

        socket.on("disconnect", function () {
            logger.debug(this.id + " Disconnected");

            var cli = clients.find(ac.TYP_WS, this.id);
            if (cli) {
                clients.remove(cli.name, "connection closed");
            }
        });
    });

    setInterval(kickIdle, 1000);
}

// The exported function is called to start the server.
// It starts a server for each individual protocol.
function start() {

    // First, we need to get our internal IP, by parsing ifconfig:
    if (process.argv.length > 2) {
        INTERNAL_IP = process.argv[2];
        startServers();
    } else {
        netIP.getNetworkIP(function (error, ip) {
            INTERNAL_IP = ip;
            startServers();
            if (error) {
                logger.error("error:", error);
            }
        }, false);
    }
}

start();
<commit_msg>starter for TCP socket server<commit_after>/*global console process require setInterval*/

// Imports and globals.
var http = require("http"),
    url = require("url"),
    net = require("net"),
    log4js = require('log4js-node'),
    dgram = require("dgram"),
    osc = require("./libs/osc.js"),
    netIP = require("./libs/netIP.js"),
    ac = require("./client.js"),
    msg = require("./msg.js"),
    querystring = require("querystring");

var DEBUG = 1,
    INTERNAL_IP = "",
    OSC_PORT = 9090,
    WS_PORT = 9091,
    TCP_PORT = 9092,
    TIMEOUT = 600000; // Seconds before kicking idle clients.

// The list of clients
var clients = new ac.AcequiaClients(TIMEOUT * 1000);

var oscServer, wsServer, tcpServer;

var logger = log4js.getLogger("acequia");

// Message routing goes here.
function onMessage(from, to, title, body, tt) {
    if (to) {
        clients.sendTo(to, from, title, body, tt);
    } else {
        clients.broadcast(from, title, body, tt);
    }
}

// Kicks any clients who we have not heard from for a while.
function kickIdle() {
    clients.clearExpired();
}

// Once we actually get our internal IP, we start the servers.
function startServers() {
    var i, from, to, title, tt, client, portOut,
    request, clientList;

    //OSC Server.
    oscServer = dgram.createSocket("udp4");

    oscServer.on("message", function (msg, rinfo) {
        var cli, oscMsgs = osc.bufferToOsc(msg),  oscMsg, i;

        for (i in oscMsgs) {
            oscMsg = oscMsgs[i];
            logger.debug(JSON.stringify(oscMsg));
            switch (oscMsg.address) {
            case msg.MSG_CONNECT:
                // TODO:  How do you send a reject message if the user already exists?
                //the second parameter when logging in is an optional "port to send to".
                portOut = (oscMsg.data[1] > 0) ? oscMsg.data[1] : rinfo.port;
                client = new ac.OSCClient(oscMsg.data[0], rinfo.address, rinfo.port, portOut, oscServer);
                clients.add(client);
                logger.debug("Added client " + oscMsg.data[0] +
                      " (OSC@" + rinfo.address + ":" + rinfo.port + ", client #" + (clients.length - 1) + ")");
                break;

            case msg.MSG_DISCONNECT:
                cli = clients.find(ac.TYP_OSC, rinfo.address, rinfo.por);
                if (cli) {
                    clients.remove(cli.name, "disconnect by user");
                }
                break;

            default:
                from = ""; // clients.find(ac.TYP_OSC, rinfo.address, rinfo.port).name;
                to = ""; // clients.get(oscMsg.data.shift()).name;
                title = oscMsg.address;
                tt = oscMsg.typeTags.slice(1);
                onMessage(from, to, title, oscMsg.data, tt);
                break;
            }
        }
    });

    // This is the bit of code that tells plasticSarcastic what ip and port we are.
    // Essentially our authentication/auto-discovery method for right now.
    oscServer.on("listening", function () {
        logger.debug("oscServer is listening on " + oscServer.address().address + ":" + oscServer.address().port);
    });

    oscServer.on("close", function () {
        logger.debug("oscServer closed");
    });

    oscServer.bind(OSC_PORT, INTERNAL_IP);

    // Websocket server:
    wsServer = require('socket.io').listen(WS_PORT);

//    wsServer.enable('browser client minification');  // send minified client
    wsServer.enable('browser client etag');          // apply etag caching logic based on version number
    wsServer.enable('browser client gzip');          // gzip the file
    wsServer.set('log level', 1);                    // reduce logging
    wsServer.set('transports', [                     // enable all transports (optional if you want flashsocket)
        'websocket',
        'flashsocket',
        'htmlfile',
        'xhr-polling',
        'jsonp-polling'
    ]);

    wsServer.sockets.on('connection', function (socket) {

        logger.debug(socket.id + " Connected");
        socket.on('message', function (data) {
            logger.debug(this.id + " Received message: " + data);

            var message = JSON.parse(data);

            switch (message.name) {
            case msg.MSG_CONNECT:
                client = new ac.WebSocketClient(message.from, this.id, socket);
                try {
                    clients.add(client);
                } catch (e) {
                    var m = new msg.AcequiaMessage("SYS", msg.MSG_CONNECT, -1);
                    wsServer.emit(m.toString());
                }
                client.send("SYS", msg.MSG_CONNECT, 1);
                break;

            case msg.MSG_DISCONNECT:
                clients.get(message.from).send("SYS", msg.MSG_DISCONNECT, 1);
                clients.remove(message.from, "disconnect by user.");
                break;

            case msg.MSG_GETCLIENTS:
                var clientList = [], cli;
                for (cli in clients.clients) {
                    clientList.push(clients.clients[cli].name);
                }
                clients.get(message.from).send("SYS", msg.MSG_GETCLIENTS, clientList);
                break;

            default:
                onMessage(message.from, message.to, message.name, message.body);
                break;
            }
        });

        socket.on("disconnect", function () {
            logger.debug(this.id + " Disconnected");

            var cli = clients.find(ac.TYP_WS, this.id);
            if (cli) {
                clients.remove(cli.name, "connection closed");
            }
        });
    });

    // Setup a tcp server
    tcpServer = net.createServer(function (socket) {

        socket.addListener("connect", function () {
            logger.debug("Connection from " + socket.remoteAddress);
        });

        socket.addListener("data", function(data) {

        });

    });

    tcpServer.listen(TCP_PORT, INTERNAL_IP);

    logger.debug("TCP erver is listening on " + INTERNAL_IP + ":" + TCP_PORT);

    setInterval(kickIdle, 1000);
}

// The exported function is called to start the server.
// It starts a server for each individual protocol.
function start() {

    // First, we need to get our internal IP, by parsing ifconfig:
    if (process.argv.length > 2) {
        INTERNAL_IP = process.argv[2];
        startServers();
    } else {
        netIP.getNetworkIP(function (error, ip) {
            INTERNAL_IP = ip;
            startServers();
            if (error) {
                logger.error("error:", error);
            }
        }, false);
    }
}

start();
<|endoftext|>


<commit_before>if (global.GENTLY) require = GENTLY.hijack(require);

var fs = require('fs');
var util = require('./util'),
    path = require('path'),
    File = require('./file'),
    MultipartParser = require('./multipart_parser').MultipartParser,
    QuerystringParser = require('./querystring_parser').QuerystringParser,
    OctetParser       = require('./octet_parser').OctetParser,
    StringDecoder = require('string_decoder').StringDecoder,
    EventEmitter = require('events').EventEmitter;

function IncomingForm() {
  if (!(this instanceof IncomingForm)) return new IncomingForm;
  EventEmitter.call(this);

  this.error = null;
  this.ended = false;

  this.maxFieldsSize = 2 * 1024 * 1024;
  this.keepExtensions = false;
  this.uploadDir = IncomingForm.UPLOAD_DIR;
  this.encoding = 'utf-8';
  this.headers = null;
  this.type = null;

  this.bytesReceived = null;
  this.bytesExpected = null;

  this._parser = null;
  this._flushing = 0;
  this._fieldsSize = 0;
};
util.inherits(IncomingForm, EventEmitter);
exports.IncomingForm = IncomingForm;

IncomingForm.UPLOAD_DIR = (function() {
  var dirs = [process.env.TMP, '/tmp', process.cwd()];
  for (var i = 0; i < dirs.length; i++) {
    var dir = dirs[i];
    var isDirectory = false;

    try {
      isDirectory = fs.statSync(dir).isDirectory();
    } catch (e) {}

    if (isDirectory) return dir;
  }
})();

IncomingForm.prototype.parse = function(req, cb) {
  this.pause = function() {
    try {
      req.pause();
    } catch (err) {
      // the stream was destroyed
      if (!this.ended) {
        // before it was completed, crash & burn
        this._error(err);
      }
      return false;
    }
    return true;
  };

  this.resume = function() {
    try {
      req.resume();
    } catch (err) {
      // the stream was destroyed
      if (!this.ended) {
        // before it was completed, crash & burn
        this._error(err);
      }
      return false;
    }

    return true;
  };

  this.writeHeaders(req.headers);

  var self = this;
  req
    .on('error', function(err) {
      self._error(err);
    })
    .on('aborted', function() {
      self.emit('aborted');
    })
    .on('data', function(buffer) {
      self.write(buffer);
    })
    .on('end', function() {
      if (self.error) {
        return;
      }

      var err = self._parser.end();
      if (err) {
        self._error(err);
      }
    });

  if (cb) {
    var fields = {}, files = {};
    this
      .on('field', function(name, value) {
        fields[name] = value;
      })
      .on('file', function(name, file) {
        files[name] = file;
      })
      .on('error', function(err) {
        cb(err, fields, files);
      })
      .on('end', function() {
        cb(null, fields, files);
      });
  }

  return this;
};

IncomingForm.prototype.writeHeaders = function(headers) {
  this.headers = headers;
  this._parseContentLength();
  this._parseContentType();
};

IncomingForm.prototype.write = function(buffer) {
  if (!this._parser) {
    this._error(new Error('unintialized parser'));
    return;
  }

  this.bytesReceived += buffer.length;
  this.emit('progress', this.bytesReceived, this.bytesExpected);

  var bytesParsed = this._parser.write(buffer);
  if (bytesParsed !== buffer.length) {
    this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed'));
  }

  return bytesParsed;
};

IncomingForm.prototype.pause = function() {
  // this does nothing, unless overwritten in IncomingForm.parse
  return false;
};

IncomingForm.prototype.resume = function() {
  // this does nothing, unless overwritten in IncomingForm.parse
  return false;
};

IncomingForm.prototype.onPart = function(part) {
  // this method can be overwritten by the user
  this.handlePart(part);
};

IncomingForm.prototype.handlePart = function(part) {
  var self = this;

  if (part.filename === undefined) {
    var value = ''
      , decoder = new StringDecoder(this.encoding);

    part.on('data', function(buffer) {
      self._fieldsSize += buffer.length;
      if (self._fieldsSize > self.maxFieldsSize) {
        self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data'));
        return;
      }
      value += decoder.write(buffer);
    });

    part.on('end', function() {
      self.emit('field', part.name, value);
    });
    return;
  }

  this._flushing++;

  var file = new File({
    path: this._uploadPath(part.filename),
    name: part.filename,
    type: part.mime,
  });

  this.emit('fileBegin', part.name, file);

  file.open();

  part.on('data', function(buffer) {
    self.pause();
    file.write(buffer, function() {
      self.resume();
    });
  });

  part.on('end', function() {
    file.end(function() {
      self._flushing--;
      self.emit('file', part.name, file);
      self._maybeEnd();
    });
  });
};

IncomingForm.prototype._parseContentType = function() {
  if (!this.headers['content-type']) {
    this._error(new Error('bad content-type header, no content-type'));
    return;
  }

  if (this.headers['content-type'].match(/octet-stream/i)) {
    this._initOctetStream();
    return;
  }

  if (this.headers['content-type'].match(/urlencoded/i)) {
    this._initUrlencoded();
    return;
  }

  if (this.headers['content-type'].match(/multipart/i)) {
    var m;
    if (m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i)) {
      this._initMultipart(m[1] || m[2]);
    } else {
      this._error(new Error('bad content-type header, no multipart boundary'));
    }
    return;
  }

  this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type']));
};

IncomingForm.prototype._error = function(err) {
  if (this.error) {
    return;
  }

  this.error = err;
  this.pause();
  this.emit('error', err);
};

IncomingForm.prototype._parseContentLength = function() {
  if (this.headers['content-length']) {
    this.bytesReceived = 0;
    this.bytesExpected = parseInt(this.headers['content-length'], 10);
  }
};

IncomingForm.prototype._newParser = function() {
  return new MultipartParser();
};

IncomingForm.prototype._initMultipart = function(boundary) {
  this.type = 'multipart';

  var parser = new MultipartParser(),
      self = this,
      headerField,
      headerValue,
      part;

  parser.initWithBoundary(boundary);

  parser.onPartBegin = function() {
    part = new EventEmitter();
    part.headers = {};
    part.name = null;
    part.filename = null;
    part.mime = null;
    headerField = '';
    headerValue = '';
  };

  parser.onHeaderField = function(b, start, end) {
    headerField += b.toString(self.encoding, start, end);
  };

  parser.onHeaderValue = function(b, start, end) {
    headerValue += b.toString(self.encoding, start, end);
  };

  parser.onHeaderEnd = function() {
    headerField = headerField.toLowerCase();
    part.headers[headerField] = headerValue;

    var m;
    if (headerField == 'content-disposition') {
      if (m = headerValue.match(/name="([^"]+)"/i)) {
        part.name = m[1];
      }

      part.filename = self._fileName(headerValue);
    } else if (headerField == 'content-type') {
      part.mime = headerValue;
    }

    headerField = '';
    headerValue = '';
  };

  parser.onHeadersEnd = function() {
    self.onPart(part);
  };

  parser.onPartData = function(b, start, end) {
    part.emit('data', b.slice(start, end));
  };

  parser.onPartEnd = function() {
    part.emit('end');
  };

  parser.onEnd = function() {
    self.ended = true;
    self._maybeEnd();
  };

  this._parser = parser;
};

IncomingForm.prototype._fileName = function(headerValue) {
  var m = headerValue.match(/filename="(.*?)"($|; )/i)
  if (!m) return;

  var filename = m[1].substr(m[1].lastIndexOf('\\') + 1);
  filename = filename.replace(/%22/g, '"');
  filename = filename.replace(/&#([\d]{4});/g, function(m, code) {
    return String.fromCharCode(code);
  });
  return filename;
};

IncomingForm.prototype._initUrlencoded = function() {
  this.type = 'urlencoded';

  var parser = new QuerystringParser()
    , self = this;

  parser.onField = function(key, val) {
    self.emit('field', key, val);
  };

  parser.onEnd = function() {
    self.ended = true;
    self._maybeEnd();
  };

  this._parser = parser;
};

IncomingForm.prototype._initOctetStream = function() {
  this.type = 'octet-stream';
  var filename = this.headers['x-file-name'];

  var file = new File({
    path: this._uploadPath(filename),
    name: filename,
    type: ''
  });

  file.open();

  this.emit('fileBegin', filename, file);

  this._flushing++;

  var self = this;

  self._parser = new OctetParser();

  self._parser.on('data', function(buffer){
	    self.pause();
	    file.write(buffer, function() {
	      self.resume();
	    });
  });
  self._parser.on('end', function(){
      self._flushing--;
      self.ended = true;
      self.emit('file', 'file', file);
      self._maybeEnd();
  });
};

IncomingForm.prototype._uploadPath = function(filename) {
  var name = '';
  for (var i = 0; i < 32; i++) {
    name += Math.floor(Math.random() * 16).toString(16);
  }

  if (this.keepExtensions) {
    var ext = path.extname(filename);
    ext     = ext.replace(/(\.[a-z0-9]+).*/, '$1')

    name += ext;
  }

  return path.join(this.uploadDir, name);
};

IncomingForm.prototype._maybeEnd = function() {
  if (!this.ended || this._flushing) {
    return;
  }

  this.emit('end');
};
<commit_msg>add mime to file type for octet-stream content-type<commit_after>if (global.GENTLY) require = GENTLY.hijack(require);

var fs = require('fs');
var util = require('./util'),
    path = require('path'),
    File = require('./file'),
    MultipartParser = require('./multipart_parser').MultipartParser,
    QuerystringParser = require('./querystring_parser').QuerystringParser,
    OctetParser       = require('./octet_parser').OctetParser,
    StringDecoder = require('string_decoder').StringDecoder,
    EventEmitter = require('events').EventEmitter;

function IncomingForm() {
  if (!(this instanceof IncomingForm)) return new IncomingForm;
  EventEmitter.call(this);

  this.error = null;
  this.ended = false;

  this.maxFieldsSize = 2 * 1024 * 1024;
  this.keepExtensions = false;
  this.uploadDir = IncomingForm.UPLOAD_DIR;
  this.encoding = 'utf-8';
  this.headers = null;
  this.type = null;

  this.bytesReceived = null;
  this.bytesExpected = null;

  this._parser = null;
  this._flushing = 0;
  this._fieldsSize = 0;
};
util.inherits(IncomingForm, EventEmitter);
exports.IncomingForm = IncomingForm;

IncomingForm.UPLOAD_DIR = (function() {
  var dirs = [process.env.TMP, '/tmp', process.cwd()];
  for (var i = 0; i < dirs.length; i++) {
    var dir = dirs[i];
    var isDirectory = false;

    try {
      isDirectory = fs.statSync(dir).isDirectory();
    } catch (e) {}

    if (isDirectory) return dir;
  }
})();

IncomingForm.prototype.parse = function(req, cb) {
  this.pause = function() {
    try {
      req.pause();
    } catch (err) {
      // the stream was destroyed
      if (!this.ended) {
        // before it was completed, crash & burn
        this._error(err);
      }
      return false;
    }
    return true;
  };

  this.resume = function() {
    try {
      req.resume();
    } catch (err) {
      // the stream was destroyed
      if (!this.ended) {
        // before it was completed, crash & burn
        this._error(err);
      }
      return false;
    }

    return true;
  };

  this.writeHeaders(req.headers);

  var self = this;
  req
    .on('error', function(err) {
      self._error(err);
    })
    .on('aborted', function() {
      self.emit('aborted');
    })
    .on('data', function(buffer) {
      self.write(buffer);
    })
    .on('end', function() {
      if (self.error) {
        return;
      }

      var err = self._parser.end();
      if (err) {
        self._error(err);
      }
    });

  if (cb) {
    var fields = {}, files = {};
    this
      .on('field', function(name, value) {
        fields[name] = value;
      })
      .on('file', function(name, file) {
        files[name] = file;
      })
      .on('error', function(err) {
        cb(err, fields, files);
      })
      .on('end', function() {
        cb(null, fields, files);
      });
  }

  return this;
};

IncomingForm.prototype.writeHeaders = function(headers) {
  this.headers = headers;
  this._parseContentLength();
  this._parseContentType();
};

IncomingForm.prototype.write = function(buffer) {
  if (!this._parser) {
    this._error(new Error('unintialized parser'));
    return;
  }

  this.bytesReceived += buffer.length;
  this.emit('progress', this.bytesReceived, this.bytesExpected);

  var bytesParsed = this._parser.write(buffer);
  if (bytesParsed !== buffer.length) {
    this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed'));
  }

  return bytesParsed;
};

IncomingForm.prototype.pause = function() {
  // this does nothing, unless overwritten in IncomingForm.parse
  return false;
};

IncomingForm.prototype.resume = function() {
  // this does nothing, unless overwritten in IncomingForm.parse
  return false;
};

IncomingForm.prototype.onPart = function(part) {
  // this method can be overwritten by the user
  this.handlePart(part);
};

IncomingForm.prototype.handlePart = function(part) {
  var self = this;

  if (part.filename === undefined) {
    var value = ''
      , decoder = new StringDecoder(this.encoding);

    part.on('data', function(buffer) {
      self._fieldsSize += buffer.length;
      if (self._fieldsSize > self.maxFieldsSize) {
        self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data'));
        return;
      }
      value += decoder.write(buffer);
    });

    part.on('end', function() {
      self.emit('field', part.name, value);
    });
    return;
  }

  this._flushing++;

  var file = new File({
    path: this._uploadPath(part.filename),
    name: part.filename,
    type: part.mime,
  });

  this.emit('fileBegin', part.name, file);

  file.open();

  part.on('data', function(buffer) {
    self.pause();
    file.write(buffer, function() {
      self.resume();
    });
  });

  part.on('end', function() {
    file.end(function() {
      self._flushing--;
      self.emit('file', part.name, file);
      self._maybeEnd();
    });
  });
};

IncomingForm.prototype._parseContentType = function() {
  if (!this.headers['content-type']) {
    this._error(new Error('bad content-type header, no content-type'));
    return;
  }

  if (this.headers['content-type'].match(/octet-stream/i)) {
    this._initOctetStream();
    return;
  }

  if (this.headers['content-type'].match(/urlencoded/i)) {
    this._initUrlencoded();
    return;
  }

  if (this.headers['content-type'].match(/multipart/i)) {
    var m;
    if (m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i)) {
      this._initMultipart(m[1] || m[2]);
    } else {
      this._error(new Error('bad content-type header, no multipart boundary'));
    }
    return;
  }

  this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type']));
};

IncomingForm.prototype._error = function(err) {
  if (this.error) {
    return;
  }

  this.error = err;
  this.pause();
  this.emit('error', err);
};

IncomingForm.prototype._parseContentLength = function() {
  if (this.headers['content-length']) {
    this.bytesReceived = 0;
    this.bytesExpected = parseInt(this.headers['content-length'], 10);
  }
};

IncomingForm.prototype._newParser = function() {
  return new MultipartParser();
};

IncomingForm.prototype._initMultipart = function(boundary) {
  this.type = 'multipart';

  var parser = new MultipartParser(),
      self = this,
      headerField,
      headerValue,
      part;

  parser.initWithBoundary(boundary);

  parser.onPartBegin = function() {
    part = new EventEmitter();
    part.headers = {};
    part.name = null;
    part.filename = null;
    part.mime = null;
    headerField = '';
    headerValue = '';
  };

  parser.onHeaderField = function(b, start, end) {
    headerField += b.toString(self.encoding, start, end);
  };

  parser.onHeaderValue = function(b, start, end) {
    headerValue += b.toString(self.encoding, start, end);
  };

  parser.onHeaderEnd = function() {
    headerField = headerField.toLowerCase();
    part.headers[headerField] = headerValue;

    var m;
    if (headerField == 'content-disposition') {
      if (m = headerValue.match(/name="([^"]+)"/i)) {
        part.name = m[1];
      }

      part.filename = self._fileName(headerValue);
    } else if (headerField == 'content-type') {
      part.mime = headerValue;
    }

    headerField = '';
    headerValue = '';
  };

  parser.onHeadersEnd = function() {
    self.onPart(part);
  };

  parser.onPartData = function(b, start, end) {
    part.emit('data', b.slice(start, end));
  };

  parser.onPartEnd = function() {
    part.emit('end');
  };

  parser.onEnd = function() {
    self.ended = true;
    self._maybeEnd();
  };

  this._parser = parser;
};

IncomingForm.prototype._fileName = function(headerValue) {
  var m = headerValue.match(/filename="(.*?)"($|; )/i)
  if (!m) return;

  var filename = m[1].substr(m[1].lastIndexOf('\\') + 1);
  filename = filename.replace(/%22/g, '"');
  filename = filename.replace(/&#([\d]{4});/g, function(m, code) {
    return String.fromCharCode(code);
  });
  return filename;
};

IncomingForm.prototype._initUrlencoded = function() {
  this.type = 'urlencoded';

  var parser = new QuerystringParser()
    , self = this;

  parser.onField = function(key, val) {
    self.emit('field', key, val);
  };

  parser.onEnd = function() {
    self.ended = true;
    self._maybeEnd();
  };

  this._parser = parser;
};

IncomingForm.prototype._initOctetStream = function() {
  this.type = 'octet-stream';
  var filename = this.headers['x-file-name'];
  var mime = this.headers['content-type'];

  var file = new File({
    path: this._uploadPath(filename),
    name: filename,
    type: mime
  });

  file.open();

  this.emit('fileBegin', filename, file);

  this._flushing++;

  var self = this;

  self._parser = new OctetParser();

  self._parser.on('data', function(buffer){
	    self.pause();
	    file.write(buffer, function() {
	      self.resume();
	    });
  });
  self._parser.on('end', function(){
      self._flushing--;
      self.ended = true;
      self.emit('file', 'file', file);
      self._maybeEnd();
  });
};

IncomingForm.prototype._uploadPath = function(filename) {
  var name = '';
  for (var i = 0; i < 32; i++) {
    name += Math.floor(Math.random() * 16).toString(16);
  }

  if (this.keepExtensions) {
    var ext = path.extname(filename);
    ext     = ext.replace(/(\.[a-z0-9]+).*/, '$1')

    name += ext;
  }

  return path.join(this.uploadDir, name);
};

IncomingForm.prototype._maybeEnd = function() {
  if (!this.ended || this._flushing) {
    return;
  }

  this.emit('end');
};
<|endoftext|>


<commit_before>var caronte = exports,
    web     = require('./passes/web-incoming');
    ws      = require('./passes/ws-incoming');

caronte.createWebProxy = createRightProxy('web');
caronte.createWsProxy  = createRightProxy('ws');

/**
 * Returns a function that creates the loader for
 * either `ws` or `web`'s  passes.
 *
 * Examples:
 *
 *    caronte.createRightProxy('ws')
 *    // => [Function]
 *
 * @param {String} Type Either 'ws' or 'web'
 *
 * @return {Function} Loader Function that when called returns an iterator for the right passes
 *
 * @api private
 */

function createRightProxy(type) {
  var passes = (type === 'ws') ? ws : web;

  return function(options) {

    passes = Object.keys(passes).map(function(pass) {
      return passes[pass];
    });

    return function(req, res /*, [head], [opts] */) {
      var self = this,
          args = [].slice.call(arguments),
          cntr = args.length - 1,
          ev   = 'caronte:' + type + ':incoming:',
          head;

      if(
        !(args[cntr] instanceof Buffer) &&
        args[cntr] !== res
      ) {
        options = args[cntr];
        cntr--;
      }

      if(args[cntr] instanceof Buffer) {
        head = args[cntr];
      }

      options.ee.emit(ev + 'begin', req, res);

      passes.some(function(pass) {
        var evnt = ev + pass.name.toLowerCase() + ':';

        options.ee.emit(evnt + 'begin', req, res);
        var val = pass(req, res, options, head);
        options.ee.emit(evnt + 'end');

        return val;
      });

      options.ee.emit(ev + 'end');
    };
  };
}

<commit_msg>Fix accidental write to global variable.<commit_after>var caronte = exports,
    web     = require('./passes/web-incoming'),
    ws      = require('./passes/ws-incoming');

caronte.createWebProxy = createRightProxy('web');
caronte.createWsProxy  = createRightProxy('ws');

/**
 * Returns a function that creates the loader for
 * either `ws` or `web`'s  passes.
 *
 * Examples:
 *
 *    caronte.createRightProxy('ws')
 *    // => [Function]
 *
 * @param {String} Type Either 'ws' or 'web'
 *
 * @return {Function} Loader Function that when called returns an iterator for the right passes
 *
 * @api private
 */

function createRightProxy(type) {
  var passes = (type === 'ws') ? ws : web;

  return function(options) {

    passes = Object.keys(passes).map(function(pass) {
      return passes[pass];
    });

    return function(req, res /*, [head], [opts] */) {
      var self = this,
          args = [].slice.call(arguments),
          cntr = args.length - 1,
          ev   = 'caronte:' + type + ':incoming:',
          head;

      if(
        !(args[cntr] instanceof Buffer) &&
        args[cntr] !== res
      ) {
        options = args[cntr];
        cntr--;
      }

      if(args[cntr] instanceof Buffer) {
        head = args[cntr];
      }

      options.ee.emit(ev + 'begin', req, res);

      passes.some(function(pass) {
        var evnt = ev + pass.name.toLowerCase() + ':';

        options.ee.emit(evnt + 'begin', req, res);
        var val = pass(req, res, options, head);
        options.ee.emit(evnt + 'end');

        return val;
      });

      options.ee.emit(ev + 'end');
    };
  };
}

<|endoftext|>


<commit_before>var fs = require('fs');
var web3 = require('web3');
var sha3_256 = require('js-sha3').sha3_256;

ChainManager = function() {
  this.chainManagerConfig = {};
  this.currentChain = {};
  this.file = "";
  this.web3 = null;
}

ChainManager.prototype.loadConfigFile = function(filename) {
  this.file = filename;
  try {
    var obj = JSON.parse(fs.readFileSync(filename));
    this.chainManagerConfig = obj;
  } catch (e) {
    console.warn("error reading " + filename + "; defaulting to empty set");
  }
  return this;
};

ChainManager.prototype.loadConfig = function(config) {
  this.chainManagerConfig = config;
  return this;
};

ChainManager.prototype.init = function(env, config) {
  web3.setProvider(new web3.providers.HttpProvider("http://" + config.rpcHost + ":" + config.rpcPort));

  var chainId = web3.eth.getBlock(0).hash;

  if (this.chainManagerConfig[chainId] === undefined) {
    this.chainManagerConfig[chainId] = {contracts: {}};
  }

  this.currentChain = this.chainManagerConfig[chainId];
  this.web3 = web3;
}

ChainManager.prototype.addContract = function(contractName, code, args, address) {
  this.currentChain.contracts[sha3_256(code + contractName + args.join(','))] = {
    name: contractName,
    address: address
  }
}

ChainManager.prototype.getContract = function(contractName, code, args) {
  return this.currentChain.contracts[sha3_256(code + contractName + args.join(','))];
}

ChainManager.prototype.save = function() {
  fs.writeFileSync(this.file, JSON.stringify(this.chainManagerConfig));
}

module.exports = ChainManager;
<commit_msg>throw error when block cannot be found<commit_after>var fs = require('fs');
var web3 = require('web3');
var sha3_256 = require('js-sha3').sha3_256;

ChainManager = function() {
  this.chainManagerConfig = {};
  this.currentChain = {};
  this.file = "";
  this.web3 = null;
}

ChainManager.prototype.loadConfigFile = function(filename) {
  this.file = filename;
  try {
    var obj = JSON.parse(fs.readFileSync(filename));
    this.chainManagerConfig = obj;
  } catch (e) {
    console.warn("error reading " + filename + "; defaulting to empty set");
  }
  return this;
};

ChainManager.prototype.loadConfig = function(config) {
  this.chainManagerConfig = config;
  return this;
};

ChainManager.prototype.init = function(env, config) {
  web3.setProvider(new web3.providers.HttpProvider("http://" + config.rpcHost + ":" + config.rpcPort));

  var block = web3.eth.getBlock(0);
  if(!block){
    throw new Error("Cannot get the genesis block, is embark blockchain running ?");
  }
  var chainId = web3.eth.getBlock(0).hash;

  if (this.chainManagerConfig[chainId] === undefined) {
    this.chainManagerConfig[chainId] = {contracts: {}};
  }

  this.currentChain = this.chainManagerConfig[chainId];
  this.web3 = web3;
}

ChainManager.prototype.addContract = function(contractName, code, args, address) {
  this.currentChain.contracts[sha3_256(code + contractName + args.join(','))] = {
    name: contractName,
    address: address
  }
}

ChainManager.prototype.getContract = function(contractName, code, args) {
  return this.currentChain.contracts[sha3_256(code + contractName + args.join(','))];
}

ChainManager.prototype.save = function() {
  fs.writeFileSync(this.file, JSON.stringify(this.chainManagerConfig));
}

module.exports = ChainManager;
<|endoftext|>