<commit_before>var angular = require('angular');
var _ = require('lodash');
var template = require('./select.html');

require('./select.css');

angular.module('cp-select')
	.directive('cpSelect', ['$timeout', function($timeout) {

		return {
			restrict: "E",
			transclude: true,
			scope: {
				collection: '=',
				placeholder: '@',
				keyModel: '@',
				transparent: '@',
				appendText: '@'
			},
			require: "ng-Model",
			template: template,
			link: function(scope, el, attr, ngModelCtrl) {
				var keyTimeout;
				var searchString = "";
				var keyModel = !_.isUndefined(attr.keyModel);
				scope.appendText = scope.appendText ? scope.appendText + ' ' : "";

				scope.showDialog = false;
				scope.selectedIndex = null;

				ngModelCtrl.$render = function() {
					var viewValue = ngModelCtrl.$viewValue ? getViewValue(ngModelCtrl.$viewValue) : "";

					if (keyModel) {
						viewValue = getOptionFromKey(viewValue);
						viewValue = viewValue ? viewValue.value : "";
					}

					viewValue = (_.isString(viewValue) && viewValue.length > 0) ? viewValue : scope.placeholder;

					el.find('.cp-select__selected').text(scope.appendText + '' + viewValue);
				}

				scope.updateModel = function(item) {
					if(keyModel) item = item.key;
					ngModelCtrl.$setViewValue(item);
					ngModelCtrl.$render();
					scope.closeDialog();
					setTimeout(function() {
						el.find('input').focus();
					})
				}

				scope.focusSelect = function() {
					el.find('.cp-select').addClass('+focus');
				}

				attr.$observe('disabled', function (value) {
					if (_.has(attr, 'ngDisabled')) {
						scope.disabled = value;
					}
					else {
						scope.disabled = _.has(attr, 'disabled');
					}
				});

				scope.keyDown = function(e) {
					var key = e.which;
					var item = ngModelCtrl.$viewValue;

					if(key !== 9) {
						e.preventDefault();
					}

					if(key === 13) {				// enter key

						scope.updateModel(scope.collection[scope.selectedIndex]);

					} else if(key === 38) { // up key

						scope.showDialog = true;
						scope.selectedIndex = _.isNull(scope.selectedIndex) ? getItemIndex(item) : scope.selectedIndex - 1;
						if (scope.selectedIndex < 0) scope.selectedIndex = 0;
						positionDialog(scope.collection[scope.selectedIndex]);

					} else if(key === 40) { // down key

						scope.showDialog = true;
						scope.selectedIndex = _.isNull(scope.selectedIndex) ? getItemIndex(item) : scope.selectedIndex + 1;
						if (scope.selectedIndex > scope.collection.length - 1) scope.selectedIndex = scope.collection.length - 1;
						positionDialog(scope.collection[scope.selectedIndex]);

					} else if(key === 27) { // escape key

						scope.closeDialog();

					} else {								// all other keys

						highlightByText(e.which);

					}
				}

				scope.toggleDialog = function() {
					var item = ngModelCtrl.$viewValue;

					if(scope.showDialog) {
						scope.showDialog = false;
						el.find('input').focus();
					} else {
						scope.selectedIndex = null;
						if(item) {
							positionDialog(item);
						}
						scope.showDialog = true;
						el.find('input').focus();
					}
				}

				scope.onBlur = function(e) {
					el.find('.cp-select').removeClass('+focus');
					scope.closeDialog();
				}

				scope.closeDialog = function(e) {
					scope.showDialog = false;
				}

				function getOptionFromKey(key) {
					return _.find(scope.collection, {key: key});
				}

				function highlightByText(charCode) {
						searchString += String.fromCharCode(charCode);
						var i = getIndexFromString(searchString);

						if(i > -1) {
							scope.selectedIndex = i;
							if(scope.showDialog) {
								positionDialog(scope.collection[scope.selectedIndex]);
							} else {
								scope.updateModel(scope.collection[scope.selectedIndex]);
							}
						}

						keyTimeout = setTimeout(function() {
							searchString = "";
						}, 1000);
				}

				function getItemIndex(item) {
					if(!item) return -1;
					var isObject = _.has(item, 'value');
					return _.findIndex(scope.collection, function(iItem) {
						return isObject ? item.key === iItem.key : item === iItem;
					});
				}

				function getIndexFromString(searchString) {
					searchString = searchString.toLowerCase();
					return _.findIndex(scope.collection, function(iItem) {
						return getViewValue(iItem).toLowerCase().indexOf(searchString) === 0;
					});
				}

				function getViewValue(option) {
					return _.isString(option.value) ? option.value : option;
				}

				function positionDialog(item) {
					var i = getItemIndex(item);

					var distanceFromEnd = scope.collection.length - i;

					if (i > 5 && distanceFromEnd < 6) {
						// Bottom 5
						if(scope.collection.length < 11) {
							// Dialog doesn't have a scroll
							scope.dialogStyle = {
								top: -2 + (36 * i * -1 - 20) + "px"
							};
						} else {
							// Dialog has a scroll
							scope.dialogStyle = {
								top: -226 - (5 - distanceFromEnd) * 36 + "px"
							};
							setTimeout(function () {
								el.find(".cp-select__menu").scrollTop(36 * i - 180);
							});
						}
					} else if (i > 5) {
						// Middle
						scope.dialogStyle = {
							top: "-203px"
						};
						setTimeout(function () {
							el.find(".cp-select__menu").scrollTop(36 * i - 180);
						});
					} else {
						// Top 5
						scope.dialogStyle = {
							top: -2 + (36 * i * -1 - 20) + "px"
						};
					}
				}
			}
		}
	}]);
<commit_msg>Provide a default to the placeholder attribute<commit_after>var angular = require('angular');
var _ = require('lodash');
var template = require('./select.html');

require('./select.css');

angular.module('cp-select')
	.directive('cpSelect', ['$timeout', function($timeout) {

		return {
			restrict: "E",
			transclude: true,
			scope: {
				collection: '=',
				placeholder: '@',
				keyModel: '@',
				transparent: '@',
				appendText: '@'
			},
			require: "ng-Model",
			template: template,
			link: function(scope, el, attr, ngModelCtrl) {
				var keyTimeout;
				var searchString = "";
				scope.placeholder = scope.placeholder || "";
				var keyModel = !_.isUndefined(attr.keyModel);
				scope.appendText = scope.appendText ? scope.appendText + ' ' : "";

				scope.showDialog = false;
				scope.selectedIndex = null;

				ngModelCtrl.$render = function() {
					var viewValue = ngModelCtrl.$viewValue ? getViewValue(ngModelCtrl.$viewValue) : "";

					if (keyModel) {
						viewValue = getOptionFromKey(viewValue);
						viewValue = viewValue ? viewValue.value : "";
					}

					viewValue = (_.isString(viewValue) && viewValue.length > 0) ? viewValue : scope.placeholder;

					el.find('.cp-select__selected').text(scope.appendText + '' + viewValue);
				}

				scope.updateModel = function(item) {
					if(keyModel) item = item.key;
					ngModelCtrl.$setViewValue(item);
					ngModelCtrl.$render();
					scope.closeDialog();
					setTimeout(function() {
						el.find('input').focus();
					})
				}

				scope.focusSelect = function() {
					el.find('.cp-select').addClass('+focus');
				}

				attr.$observe('disabled', function (value) {
					if (_.has(attr, 'ngDisabled')) {
						scope.disabled = value;
					}
					else {
						scope.disabled = _.has(attr, 'disabled');
					}
				});

				scope.keyDown = function(e) {
					var key = e.which;
					var item = ngModelCtrl.$viewValue;

					if(key !== 9) {
						e.preventDefault();
					}

					if(key === 13) {				// enter key

						scope.updateModel(scope.collection[scope.selectedIndex]);

					} else if(key === 38) { // up key

						scope.showDialog = true;
						scope.selectedIndex = _.isNull(scope.selectedIndex) ? getItemIndex(item) : scope.selectedIndex - 1;
						if (scope.selectedIndex < 0) scope.selectedIndex = 0;
						positionDialog(scope.collection[scope.selectedIndex]);

					} else if(key === 40) { // down key

						scope.showDialog = true;
						scope.selectedIndex = _.isNull(scope.selectedIndex) ? getItemIndex(item) : scope.selectedIndex + 1;
						if (scope.selectedIndex > scope.collection.length - 1) scope.selectedIndex = scope.collection.length - 1;
						positionDialog(scope.collection[scope.selectedIndex]);

					} else if(key === 27) { // escape key

						scope.closeDialog();

					} else {								// all other keys

						highlightByText(e.which);

					}
				}

				scope.toggleDialog = function() {
					var item = ngModelCtrl.$viewValue;

					if(scope.showDialog) {
						scope.showDialog = false;
						el.find('input').focus();
					} else {
						scope.selectedIndex = null;
						if(item) {
							positionDialog(item);
						}
						scope.showDialog = true;
						el.find('input').focus();
					}
				}

				scope.onBlur = function(e) {
					el.find('.cp-select').removeClass('+focus');
					scope.closeDialog();
				}

				scope.closeDialog = function(e) {
					scope.showDialog = false;
				}

				function getOptionFromKey(key) {
					return _.find(scope.collection, {key: key});
				}

				function highlightByText(charCode) {
						searchString += String.fromCharCode(charCode);
						var i = getIndexFromString(searchString);

						if(i > -1) {
							scope.selectedIndex = i;
							if(scope.showDialog) {
								positionDialog(scope.collection[scope.selectedIndex]);
							} else {
								scope.updateModel(scope.collection[scope.selectedIndex]);
							}
						}

						keyTimeout = setTimeout(function() {
							searchString = "";
						}, 1000);
				}

				function getItemIndex(item) {
					if(!item) return -1;
					var isObject = _.has(item, 'value');
					return _.findIndex(scope.collection, function(iItem) {
						return isObject ? item.key === iItem.key : item === iItem;
					});
				}

				function getIndexFromString(searchString) {
					searchString = searchString.toLowerCase();
					return _.findIndex(scope.collection, function(iItem) {
						return getViewValue(iItem).toLowerCase().indexOf(searchString) === 0;
					});
				}

				function getViewValue(option) {
					return _.isString(option.value) ? option.value : option;
				}

				function positionDialog(item) {
					var i = getItemIndex(item);

					var distanceFromEnd = scope.collection.length - i;

					if (i > 5 && distanceFromEnd < 6) {
						// Bottom 5
						if(scope.collection.length < 11) {
							// Dialog doesn't have a scroll
							scope.dialogStyle = {
								top: -2 + (36 * i * -1 - 20) + "px"
							};
						} else {
							// Dialog has a scroll
							scope.dialogStyle = {
								top: -226 - (5 - distanceFromEnd) * 36 + "px"
							};
							setTimeout(function () {
								el.find(".cp-select__menu").scrollTop(36 * i - 180);
							});
						}
					} else if (i > 5) {
						// Middle
						scope.dialogStyle = {
							top: "-203px"
						};
						setTimeout(function () {
							el.find(".cp-select__menu").scrollTop(36 * i - 180);
						});
					} else {
						// Top 5
						scope.dialogStyle = {
							top: -2 + (36 * i * -1 - 20) + "px"
						};
					}
				}
			}
		}
	}]);
<|endoftext|>


<commit_before>'use strict';

var exports = module.exports = {};

var Response = exports.Response = function Response(channel) {
  this.channel = channel;
  this.data = '';
  this.sent = false;
};

Response.prototype.write = function write(data) {
  this.data += data;
};

Response.prototype.end = function end(data) {
  if (!this.sent) {
    this.data += (data || '');
    (this.data.length > 0) && this.channel.send(this.data);
    this.sent = true;
  }
};

Response.prototype.random = function random(arr) {
  var data = arr[Math.floor(arr.length * Math.random())]
  this.end(data);
};

exports.response = Response;
<commit_msg>Add Response.writef method<commit_after>'use strict';

var lfmt = require('lfmt');

var Response = exports.Response = function Response(channel) {
  this.channel = channel;
  this.data = '';
  this.sent = false;
};

Response.prototype.write = function write(data) {
  this.data += data;
};

Response.prototype.writef = function writef(data, context) {
  this.data += lfmt.format(data, context);
};

Response.prototype.end = function end(data) {
  if (!this.sent) {
    this.data += (data || '');
    (this.data.length > 0) && this.channel.send(this.data);
    this.sent = true;
  }
};

Response.prototype.random = function random(arr) {
  var data = arr[Math.floor(arr.length * Math.random())]
  this.end(data);
};

exports.response = Response;
<|endoftext|>


<commit_before>export function selectHistoryState(state) {
  return state.history
}
export function selectActiveKey({ activeKey, key }) {
  if (!key[activeKey]) throw new Error(`Missing history for key ${activeKey}.`)
  return key[activeKey]
}
export function selectLastKey({ lastKey, key }) {
  if (!key[lastKey]) throw new Error(`Missing history for key ${lastKey}.`)
  return key[lastKey]
}
export function selectActiveKeyDefault(state) {
  return selectActiveKey(selectHistoryState(state))
}
export function historyMatch(reduxHistory, windowHistory) {
  if (!windowHistory || !windowHistory.id) throw new Error('Missing window.history.state')
  const activeKey = selectActiveKey(reduxHistory)
  return activeKey.id === windowHistory.id
}
export function keyMatch(reduxHistory, windowHistory) {
  return reduxHistory.activeKey === windowHistory.id
}
export function getKeyIndex(reduxHistory) {
  return selectActiveKey(reduxHistory).index
}
export function getLastIndex(reduxHistory) {
  return selectLastKey(reduxHistory).index
}
export function getLength(reduxHistory) {
  if (!reduxHistory.lastKey) return 0
  return getLastIndex(reduxHistory) + 1
}
export function activeLastMatch({ activeKey, lastKey }) {
  return activeKey === lastKey
}
export function isNewHistory(reduxHistory, browserState) {
  const length = getLength(reduxHistory)
  return activeLastMatch(reduxHistory) && browserState.length === (length - 1)
}
export function browserHistory(reduxHistory) {
  return {
    ...selectActiveKey(reduxHistory),
    length: getLength(reduxHistory),
  }
}
export function lengthMatch(reduxHistory, windowHistory) {
  return getLength(reduxHistory) === windowHistory.length
}
<commit_msg>generator functions<commit_after>import isUndefined from 'lodash/isUndefined'
import { initState } from './reducer'

export function selectHistoryState(state) {
  return state.history
}
export function getKey(keyType) {
  if (isUndefined(initState[keyType])) throw new Error('Invalid keyType.')
  return state => {
    const key = state[keyType]
    if (!key) throw new Error(`Missing history for ${keyType} key ${key}.`)
    return key
  }
}
export const selectActiveKey = getKey('activeKey')
export const selectFirstKey = getKey('firstKey')
export const selectLastKey = getKey('lastKey')
export function getIndex(selectKey) {
  return state => selectKey(state).index
}
export const getFirstIndex = getIndex(selectFirstKey)
export const getKeyIndex = getIndex(selectActiveKey)
export const getLastIndex = getIndex(selectLastKey)
export function selectActiveKeyDefault(state) {
  return selectActiveKey(selectHistoryState(state))
}
export function historyMatch(reduxHistory, windowHistory) {
  if (!windowHistory || !windowHistory.id) throw new Error('Missing window.history.state')
  const activeKey = selectActiveKey(reduxHistory)
  return activeKey.id === windowHistory.id
}
export function keyMatch(reduxHistory, windowHistory) {
  return reduxHistory.activeKey === windowHistory.id
}
export function getLength(reduxHistory) {
  if (!reduxHistory.lastKey) return 0
  return getLastIndex(reduxHistory) + 1
}
export function activeLastMatch({ activeKey, lastKey }) {
  return activeKey === lastKey
}
export function isNewHistory(reduxHistory, browserState) {
  const length = getLength(reduxHistory)
  return activeLastMatch(reduxHistory) && browserState.length === (length - 1)
}
export function browserHistory(reduxHistory) {
  return {
    ...selectActiveKey(reduxHistory),
    length: getLength(reduxHistory),
  }
}
export function lengthMatch(reduxHistory, windowHistory) {
  return getLength(reduxHistory) === windowHistory.length
}
export function browserHasHistory(windowHistory) {
  return windowHistory.state && windowHistory.state.id
}
<|endoftext|>


<commit_before>'use strict';
/**
 * @file response.js
 * @author Wes Todd
 * @module nighthawk
 */

var EventEmitter = require('events');
var inherits = require('inherits');
var url = require('url');
var noop = function noop () {};

/**
 * Response
 *
 * @constructor Response
 * @memberof module:nighthawk
 */
var Response = module.exports = function Response () {
	this.app = null;
	this.locals = Object.create(null);
	this.headersSent = false;
	this.statusCode = null;
	this.statusMessage = '';
	this.finished = false;
	this.headersSent = false;
	this.sendDate = false;
};
inherits(Response, EventEmitter);

/**
 * Redirect to a different route
 *
 * @function redirect
 * @memberof module:nighthawk.Response
 * @instance
 * @param {Number} statusCode - Optional status code discarded by nighthawk but handled for backend parity
 * @param {String} u - The new url
 */
Response.prototype.redirect = function (statusCode, u) {
	// In a timeout because page.js did it, but I believe it is better
	// to let the current route handler finish its stuff before starting
	// another round of routing, otherwise we could get some weird behavior.

	if (typeof statusCode === 'string') {
		u = statusCode;
		statusCode = 302;
	}
	this.status(statusCode);

	setTimeout(function () {
		// Convert the url string into an object
		// before passing it along to the router
		u = url.parse(u);
		this.app._processRequest(u, true);
	}.bind(this), 0);
};

Response.prototype.status = function (code) {
	this.statusCode = code;
	return this;
};

// Noops for parity with backend request object
Response.prototype.links =
Response.prototype.send =
Response.prototype.json =
Response.prototype.jsonp =
Response.prototype.sendStatus =
Response.prototype.sendFile =
Response.prototype.download =
Response.prototype.contentType =
Response.prototype.type =
Response.prototype.format =
Response.prototype.attachment =
Response.prototype.append =
Response.prototype.set =
Response.prototype.header =
Response.prototype.get =
Response.prototype.clearCookie =
Response.prototype.cookie =
Response.prototype.location =
Response.prototype.vary =
Response.prototype.render =
Response.prototype.addTrailers =
Response.prototype.end =
Response.prototype.getHeader =
Response.prototype.getHeaderNames =
Response.prototype.getHeaders =
Response.prototype.hasHeader =
Response.prototype.removeHeader =
Response.prototype.setHeader =
Response.prototype.setTimeout =
Response.prototype.write =
Response.prototype.writeContinue =
Response.prototype.writeHead =
noop;
<commit_msg>moved comment that got displaced in a merge<commit_after>'use strict';
/**
 * @file response.js
 * @author Wes Todd
 * @module nighthawk
 */

var EventEmitter = require('events');
var inherits = require('inherits');
var url = require('url');
var noop = function noop () {};

/**
 * Response
 *
 * @constructor Response
 * @memberof module:nighthawk
 */
var Response = module.exports = function Response () {
	this.app = null;
	this.locals = Object.create(null);
	this.headersSent = false;
	this.statusCode = null;
	this.statusMessage = '';
	this.finished = false;
	this.headersSent = false;
	this.sendDate = false;
};
inherits(Response, EventEmitter);

/**
 * Redirect to a different route
 *
 * @function redirect
 * @memberof module:nighthawk.Response
 * @instance
 * @param {Number} statusCode - Optional status code discarded by nighthawk but handled for backend parity
 * @param {String} u - The new url
 */
Response.prototype.redirect = function (statusCode, u) {
	if (typeof statusCode === 'string') {
		u = statusCode;
		statusCode = 302;
	}
	this.status(statusCode);

	// In a timeout because page.js did it, but I believe it is better
	// to let the current route handler finish its stuff before starting
	// another round of routing, otherwise we could get some weird behavior.
	setTimeout(function () {
		// Convert the url string into an object
		// before passing it along to the router
		u = url.parse(u);
		this.app._processRequest(u, true);
	}.bind(this), 0);
};

Response.prototype.status = function (code) {
	this.statusCode = code;
	return this;
};

// Noops for parity with backend request object
Response.prototype.links =
Response.prototype.send =
Response.prototype.json =
Response.prototype.jsonp =
Response.prototype.sendStatus =
Response.prototype.sendFile =
Response.prototype.download =
Response.prototype.contentType =
Response.prototype.type =
Response.prototype.format =
Response.prototype.attachment =
Response.prototype.append =
Response.prototype.set =
Response.prototype.header =
Response.prototype.get =
Response.prototype.clearCookie =
Response.prototype.cookie =
Response.prototype.location =
Response.prototype.vary =
Response.prototype.render =
Response.prototype.addTrailers =
Response.prototype.end =
Response.prototype.getHeader =
Response.prototype.getHeaderNames =
Response.prototype.getHeaders =
Response.prototype.hasHeader =
Response.prototype.removeHeader =
Response.prototype.setHeader =
Response.prototype.setTimeout =
Response.prototype.write =
Response.prototype.writeContinue =
Response.prototype.writeHead =
noop;
<|endoftext|>


<commit_before>var Stream = require('stream');
var util = require('util');

var Response = module.exports = function (res) {
    this.offset = 0;
    this.readable = true;
};

util.inherits(Response, Stream);

var capable = {
    streaming : false,
    status2 : true
};

function parseHeaders (res) {
	var headers = {};

	res.headers.forEach(function (h) {
		headers[h.name.toLowerCase()] = h.value;
	});

    return headers;
}

Response.prototype.getResponse = function (res) {
	return res.data;
}

Response.prototype.getHeader = function (key) {
    return this.headers[key.toLowerCase()];
};

Response.prototype.handle = function (req) {
	var self = this;

	req.onerror = function (error) {
        if (!(error instanceof Error)) {
            error = new Error(error || 'error')
        }
		self.emit('ready');
		self.emit('error', error);
	};

	req.onabort = function (error) {
        if (!(error instanceof Error)) {
            error = new Error(error || 'abort')
        }
		self.emit('ready');
		self.emit('error', error);
	};

	req.ontimed = function (error) {
        if (!(error instanceof Error)) {
            error = new Error(error || 'timed')
        }
		self.emit('ready');
		self.emit('error', error);
	};

	req.onload = function (res) {
		self.statusCode = res.code;
		self.headers = parseHeaders(res);

		self.emit('ready');

		self._emitData(res);

		self.emit('end');
		self.emit('close');
	};
};

Response.prototype._emitData = function (res) {
    var respBody = this.getResponse(res);

	if (!respBody) {
		return;
	}

    if (respBody instanceof ArrayBuffer) {
        this.emit('data', new Uint8Array(respBody, this.offset));
        this.offset = respBody.byteLength;
        return;
    } else
    if (respBody.length > this.offset) {
        this.emit('data', respBody.slice(this.offset));
        this.offset = respBody.length;
    }
};

var isArray = Array.isArray || function (xs) {
    return Object.prototype.toString.call(xs) === '[object Array]';
};
<commit_msg>Extract the message.<commit_after>var Stream = require('stream');
var util = require('util');

var Response = module.exports = function (res) {
    this.offset = 0;
    this.readable = true;
};

util.inherits(Response, Stream);

var capable = {
    streaming : false,
    status2 : true
};

function parseHeaders (res) {
	var headers = {};

	res.headers.forEach(function (h) {
		headers[h.name.toLowerCase()] = h.value;
	});

    return headers;
}

Response.prototype.getResponse = function (res) {
	return res.data;
}

Response.prototype.getHeader = function (key) {
    return this.headers[key.toLowerCase()];
};

Response.prototype.handle = function (req) {
	var self = this;

	req.onerror = function (error) {
        if (!(error instanceof Error)) {
            error = new Error(error || 'error')
        }
		self.emit('ready');
		self.emit('error', error);
	};

	req.onabort = function (error) {
        if (!(error instanceof Error)) {
            error = new Error(error || 'abort')
        }
		self.emit('ready');
		self.emit('error', error);
	};

	req.ontimed = function (error) {
        if (!(error instanceof Error)) {
            error = new Error(error || 'timed')
        }
		self.emit('ready');
		self.emit('error', error);
	};

	req.onload = function (res) {
		self.statusCode = res.code;
        self.statusMessage = res.message;
		self.headers = parseHeaders(res);

		self.emit('ready');

		self._emitData(res);

		self.emit('end');
		self.emit('close');
	};
};

Response.prototype._emitData = function (res) {
    var respBody = this.getResponse(res);

	if (!respBody) {
		return;
	}

    if (respBody instanceof ArrayBuffer) {
        this.emit('data', new Uint8Array(respBody, this.offset));
        this.offset = respBody.byteLength;
        return;
    } else
    if (respBody.length > this.offset) {
        this.emit('data', respBody.slice(this.offset));
        this.offset = respBody.length;
    }
};

var isArray = Array.isArray || function (xs) {
    return Object.prototype.toString.call(xs) === '[object Array]';
};
<|endoftext|>


<commit_before>var ONE_PLUS_ULP  = 1.0 + Math.pow(2, -52)
var ONE_MINUS_ULP = 1.0 - Math.pow(2, -53)
var DENORMAL      = Math.pow(2, -1021)
var MIN_FLOAT     = Number.MIN_VALUE
var MAX_FLOAT     = Number.MAX_VALUE

function roundUp(x) {
  x = +x
  if(x > +0) {
    if(x < DENORMAL) {
      return +(x + MIN_FLOAT)
    }
    return +(x * ONE_PLUS_ULP)
  } else if(x < 0) {
    if(x > -DENORMAL) {
      return +(x + MIN_FLOAT)
    } else if(x === -Infinity) {
      return -MAX_FLOAT
    }
    return +(x * ONE_MINUS_ULP)
  } else {
    return +MIN_FLOAT
  }
}
exports.up = roundUp

function roundDown(x) {
  x = +x
  if(x > 0) {
    if(x < DENORMAL) {
      return +(x - MIN_FLOAT)
    } else if(x === Infinity) {
      return +MAX_FLOAT
    }
    return +(x * ONE_MINUS_ULP)
  } else if(x < 0) {
    if(x > -DENORMAL) {
      return +(x - MIN_FLOAT)
    }
    return +(x * ONE_PLUS_ULP)
  } else {
    return -MIN_FLOAT
  }
}
exports.down = roundDown
<commit_msg>remove old junk<commit_after><|endoftext|>


<commit_before>'use strict';

import { SerialPort } from 'serialport';
import Promise from 'es6-promises';

let serialPort;

class Dump {
  parse(data) {
    console.log(data.toString('hex'));
  }
}

export function start(bus, parser=new Dump()) {
  if (!bus) {
    throw new Error('bus is required!');
  }
  let port = process.env.SERIAL_PORT;
  let baudrate = process.env.SERIAL_BAUDRATE || 57600;
  if (!port) {
    throw new Error('Seril port is required! Set SERIAL_PORT environment variable.');
  }
  serialPort = new SerialPort(port, {
    baudrate: baudrate
  }, false);
  return new Promise((resolve, reject) => {
    serialPort.open(e => {
      if (e) {
        reject(e);
        return;
      }
      console.log('Starting Seril Port Listening...');
      serialPort.on('data', data => {
        if (parser) {
          parser.parse(data);
        }
      });
    });
    resolve();
  });
}

export function write(data) {
  return new Promise((resolve, reject) => {
    if (!serialPort && serialPort.isOpen()) {
      serialPort.write(data, e => {
        if (e) {
          reject(e);
        } else {
          resolve();
        }
      });
    } else {
      reject('Serial port is closed');
    }
  });
}

export function stop() {
  return new Promise((resolve, reject) => {
    if (!serialPort && serialPort.isOpen()) {
      serialPort.close(e => {
        if (e) {
          reject(e);
        } else {
          serialPort = undefined;
          resolve();
        }
      });
    } else {
      resolve();
    }
  });
}
<commit_msg>Allow a serial module client to silently inactivate the serial module when SERIAL_PORT is missing<commit_after>'use strict';

import { SerialPort } from 'serialport';
import Promise from 'es6-promises';

let serialPort;

class Dump {
  parse(data) {
    console.log(data.toString('hex'));
  }
}

export function start(bus, parser=new Dump()) {
  if (!bus) {
    throw new Error('bus is required!');
  }
  let port = process.env.SERIAL_PORT;
  let baudrate = process.env.SERIAL_BAUDRATE || 57600;
  if (!port) {
    console.log('Serial port is inactivated...');
    return new Promise(resolve => { resolve(); });
  }
  serialPort = new SerialPort(port, {
    baudrate: baudrate
  }, false);
  return new Promise((resolve, reject) => {
    serialPort.open(e => {
      if (e) {
        reject(e);
        return;
      }
      console.log('Starting Seril Port Listening...');
      serialPort.on('data', data => {
        if (parser) {
          parser.parse(data);
        }
      });
    });
    resolve();
  });
}

export function write(data) {
  return new Promise((resolve, reject) => {
    if (!serialPort && serialPort.isOpen()) {
      serialPort.write(data, e => {
        if (e) {
          reject(e);
        } else {
          resolve();
        }
      });
    } else {
      reject('Serial port is closed');
    }
  });
}

export function stop() {
  return new Promise((resolve, reject) => {
    if (!serialPort && serialPort.isOpen()) {
      serialPort.close(e => {
        if (e) {
          reject(e);
        } else {
          serialPort = undefined;
          resolve();
        }
      });
    } else {
      resolve();
    }
  });
}
<|endoftext|>


<commit_before>var mongoose = require('mongoose'),
	db = mongoose.connect(process.env.DB_URL),
	Schema = mongoose.Schema,
	Item = new Schema({
		name: String
	}),
	ShoppingList = new Schema({
		name	: String,
		items	: [Item]
	}),
	SlModel = mongoose.model('SlModel', ShoppingList),
	populateModel = function(model, o) {
		model = model || new SlModel();
		model.name = o.name;
		model.items = o.items || [];
		return model;
	};

console.log('DB_URL: ' + process.env.DB_URL);

exports.SlDb = function() {};

exports.SlDb.prototype = {

	add: function(slData, cb) {
		var sl = populateModel(sl, slData);
		sl.save(function(err) {
			cb(err, sl);
		});
	},

	update: function(id, slData, cb) {
		this.findById(id, function(err, sl) {
			if (!sl) {
				cb('not_found');
				return;
			}
			populateModel(sl, slData);
			sl.save(function(err) {
				cb(err, sl);
			});
		});
	},

	findById: function(id, cb) {
		SlModel.findById(id, function(err, sl) {
			cb(err, sl);
		});
	},

	find: function(options, cb) {
		options = options || {};
		options.skip  = options.skip || 0;
		options.limit = options.limit || 25;
		SlModel.find({}).skip(options.skip).limit(options.limit).exec(function(err, sls) {
			cb(err, sls);
		});
	},

	deleteById: function(id, cb) {
		this.findById(id, function(err, sl) {
			if (err || !sl) {
				cb('not_found');
				return;
			}
			sl.remove();
			cb(null, sl);
		});
	},

	delete: function(cb) {
		this.find({}, function(err, sls) {
			if (err) throw err;
			sls.forEach(function(sl) {
				sl.remove();
			});
			cb();
		});
	},

	close: function() {
		db.disconnect();
	}
};
<commit_msg>set a default DB_URL if none provided<commit_after>var mongoose = require('mongoose'),
	url = process.env.DB_URL || 'mongodb://rd:rd@ds031587.mongolab.com:31587/rd',
	db = mongoose.connect(url),
	Schema = mongoose.Schema,
	Item = new Schema({
		name: String
	}),
	ShoppingList = new Schema({
		name	: String,
		items	: [Item]
	}),
	SlModel = mongoose.model('SlModel', ShoppingList),
	populateModel = function(model, o) {
		model = model || new SlModel();
		model.name = o.name;
		model.items = o.items || [];
		return model;
	};

console.log('url: ' + url);

exports.SlDb = function() {};

exports.SlDb.prototype = {

	add: function(slData, cb) {
		var sl = populateModel(sl, slData);
		sl.save(function(err) {
			cb(err, sl);
		});
	},

	update: function(id, slData, cb) {
		this.findById(id, function(err, sl) {
			if (!sl) {
				cb('not_found');
				return;
			}
			populateModel(sl, slData);
			sl.save(function(err) {
				cb(err, sl);
			});
		});
	},

	findById: function(id, cb) {
		SlModel.findById(id, function(err, sl) {
			cb(err, sl);
		});
	},

	find: function(options, cb) {
		options = options || {};
		options.skip  = options.skip || 0;
		options.limit = options.limit || 25;
		SlModel.find({}).skip(options.skip).limit(options.limit).exec(function(err, sls) {
			cb(err, sls);
		});
	},

	deleteById: function(id, cb) {
		this.findById(id, function(err, sl) {
			if (err || !sl) {
				cb('not_found');
				return;
			}
			sl.remove();
			cb(null, sl);
		});
	},

	delete: function(cb) {
		this.find({}, function(err, sls) {
			if (err) throw err;
			sls.forEach(function(sl) {
				sl.remove();
			});
			cb();
		});
	},

	close: function() {
		db.disconnect();
	}
};
<|endoftext|>


<commit_before>var anydbsql = require('anydb-sql'),
    RSVP = require('rsvp');

var Repository = function(dbURL) {
  this.url = dbURL;
  this.db = anydbsql({url: this.url});

  this.models = {
    Addon: this.db.define({
      name: 'addons',
      columns: {
        id: {primaryKey: true},
        name: {},
        doc: {}
      }
    }),
    Metric: this.db.define({
      name: 'metrics',
      columns: {
        id: {primaryKey: true},
        created: {},
        metric: {},
        value: {}
      }
    })
  };
};

Repository.prototype.getAll = function() {
  var addon = this.models.Addon;

  var promise = new RSVP.Promise(function(resolve, reject) {
    addon.select('*')
      .order(addon.name.ascending)
      .all(function(err, rows) {
        if (err) reject(new Error(err));
        resolve(rows);
      });
  });
  return promise;
};

Repository.prototype.createOrReplace = function(item) {
  var self = this,
      addon = this.models.Addon;

  var promise = new RSVP.Promise(function(resolve) {
    self.db.transaction(function(tx) {
      addon.delete().where({name: item.name}).execWithin(tx);

      addon.insert({name: item.name, doc: JSON.stringify(item)})
        .execWithin(tx);
    });
    resolve(item.name);
  });
  return promise;
};

Repository.prototype.count = function() {
  var addon = this.models.Addon;
  var promise = new RSVP.Promise(function(resolve, reject) {
    addon.select(addon.count()).get(function(err, row) {
      if (err) reject(new Error(err));
      resolve(row);
    });

  });
  return promise;
};

Repository.prototype.saveMetric = function(name, value) {
  var self = this,
      metric = this.models.Metric;
  var promise = new RSVP.Promise(function(resolve) {
    self.db.transaction(function(tx) {
      metric.insert(metric.metric.value(name), metric.value.value(value))
        .execWithin(tx);
    });
    resolve(name, value);
  });
  return promise;
};

Repository.prototype.getMetric = function(name) {
  var metric = this.models.Metric;

  var promise = new RSVP.Promise(function(resolve, reject) {
    metric.select(metric.created).select(metric.value)
      .where({metric: name})
      .order(metric.created.ascending)
      .all(function(err, rows) {
        if (err) reject(new Error(err));
        resolve(rows);
      });
  });
  return promise;
};

// Testing
// var repo = new Repository('postgres://gcollazo:@localhost:5432/emaddons');
// repo.getAll({skipPrivateRepos:true}).then(function(results) {
//   // console.log(results);
// });

module.exports = Repository;
<commit_msg>Fix errors and remove testing code<commit_after>var anydbsql = require('anydb-sql'),
    RSVP = require('rsvp');

var Repository = function(dbURL) {
  this.url = dbURL;
  this.db = anydbsql({url: this.url});

  this.models = {
    Addon: this.db.define({
      name: 'addons',
      columns: {
        id: {primaryKey: true},
        name: {},
        doc: {}
      }
    }),
    Metric: this.db.define({
      name: 'metrics',
      columns: {
        id: {primaryKey: true},
        created: {},
        metric: {},
        value: {}
      }
    })
  };
};

Repository.prototype.getAll = function() {
  var addon = this.models.Addon;

  var promise = new RSVP.Promise(function(resolve, reject) {
    addon.select('*')
      .order(addon.name.ascending)
      .all(function(err, rows) {
        if (err) reject(err);
        resolve(rows);
      });
  });
  return promise;
};

Repository.prototype.createOrReplace = function(item) {
  var self = this,
      addon = this.models.Addon;

  var promise = new RSVP.Promise(function(resolve) {
    self.db.transaction(function(tx) {
      addon.delete().where({name: item.name}).execWithin(tx);

      addon.insert({name: item.name, doc: JSON.stringify(item)})
        .execWithin(tx);
    });
    resolve(item.name);
  });
  return promise;
};

Repository.prototype.count = function() {
  var addon = this.models.Addon;
  var promise = new RSVP.Promise(function(resolve, reject) {
    addon.select(addon.count()).get(function(err, row) {
      if (err) reject(err);
      resolve(row);
    });

  });
  return promise;
};

Repository.prototype.saveMetric = function(name, value) {
  var self = this,
      metric = this.models.Metric;
  var promise = new RSVP.Promise(function(resolve) {
    self.db.transaction(function(tx) {
      metric.insert(metric.metric.value(name), metric.value.value(value))
        .execWithin(tx);
    });
    resolve(name, value);
  });
  return promise;
};

Repository.prototype.getMetric = function(name) {
  var metric = this.models.Metric;

  var promise = new RSVP.Promise(function(resolve, reject) {
    metric.select(metric.created).select(metric.value)
      .where({metric: name})
      .order(metric.created.ascending)
      .all(function(err, rows) {
        if (err) reject(err);
        resolve(rows);
      });
  });
  return promise;
};

module.exports = Repository;
<|endoftext|>


<commit_before>import Express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import config from './config';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import Html from './helpers/Html';
import PrettyError from 'pretty-error';
import http from 'http';
import herokuProxy from 'heroku-proxy';

import { match } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect';
import createHistory from 'react-router/lib/createMemoryHistory';
import {Provider} from 'react-redux';
import getRoutes from './routes';

const targetUrl = 'https://' + config.apiHost + config.apiPort;
const pretty = new PrettyError();
const app = new Express();
const server = new http.Server(app);

const proxy = herokuProxy({
  hostname: targetUrl,
  port    : 5001,
  protocol: 'https'
});

app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));

app.use(Express.static(path.join(__dirname, '..', 'static')));

// Proxy to API server
app.use('/api', (req, res) => {
  console.log(req.url);
  proxy.web(req, res, {hostname: targetUrl});
});

app.use('/ws', (req, res) => {
  proxy.web(req, res, {hostname: targetUrl + '/ws'});
});

server.on('upgrade', (req, socket, head) => {
  proxy.ws(req, socket, head);
});

// added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527
proxy.on('error', (error, req, res) => {
  let json;
  if (error.code !== 'ECONNRESET') {
    console.error('proxy error', error);
  }
  if (!res.headersSent) {
    res.writeHead(500, {'content-type': 'application/json'});
  }

  json = {error: 'proxy_error', reason: error.message};
  res.end(JSON.stringify(json));
});

app.use((req, res) => {
  if (__DEVELOPMENT__) {
    // Do not cache webpack stats: the script file would change since
    // hot module replacement is enabled in the development env
    webpackIsomorphicTools.refresh();
  }
  const client = new ApiClient(req);
  const memoryHistory = createHistory(req.originalUrl);
  const store = createStore(memoryHistory, client);
  const history = syncHistoryWithStore(memoryHistory, store);

  function hydrateOnClient() {
    res.send('<!doctype html>\n' +
      ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>));
  }

  if (__DISABLE_SSR__) {
    hydrateOnClient();
    return;
  }

  match({ history, routes: getRoutes(store), location: req.originalUrl }, (error, redirectLocation, renderProps) => {
    if (redirectLocation) {
      res.redirect(redirectLocation.pathname + redirectLocation.search);
    } else if (error) {
      console.error('ROUTER ERROR:', pretty.render(error));
      res.status(500);
      hydrateOnClient();
    } else if (renderProps) {
      loadOnServer({...renderProps, store, helpers: {client}}).then(() => {
        const component = (
          <Provider store={store} key="provider">
            <ReduxAsyncConnect {...renderProps} />
          </Provider>
        );

        res.status(200);

        global.navigator = {userAgent: req.headers['user-agent']};

        res.send('<!doctype html>\n' +
          ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>));
      });
    } else {
      res.status(404).send('Not found');
    }
  });
});

if (config.port) {
  server.listen(config.port, (err) => {
    if (err) {
      console.error(err);
    }
    console.info('==> 💻  Open http://%s:%s in a browser to view the app.', config.host, config.port);
  });
} else {
  console.error('==>     ERROR: No PORT environment variable has been specified');
}
<commit_msg>fix this proxy server<commit_after>import Express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import config from './config';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import Html from './helpers/Html';
import PrettyError from 'pretty-error';
import http from 'http';
import herokuProxy from 'heroku-proxy';

import { match } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect';
import createHistory from 'react-router/lib/createMemoryHistory';
import {Provider} from 'react-redux';
import getRoutes from './routes';

const targetUrl = 'https://' + config.apiHost + config.apiPort;
const pretty = new PrettyError();
const app = new Express();
const server = new http.Server(app);

const proxy = herokuProxy({
  hostname: targetUrl,
  port    : 5001,
  protocol: 'https'
});

app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));

app.use(Express.static(path.join(__dirname, '..', 'static')));

// Proxy to API server
app.use('/api', (req, res) => {
  console.log(req.url);
  proxy.web(req, res, {hostname: targetUrl});
});

app.use('/ws', (req, res) => {
  proxy.web(req, res, {hostname: targetUrl + '/ws'});
});

server.on('upgrade', (req, socket, head) => {
  proxy.ws(req, socket, head);
});

// added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527

app.use((req, res) => {
  if (__DEVELOPMENT__) {
    // Do not cache webpack stats: the script file would change since
    // hot module replacement is enabled in the development env
    webpackIsomorphicTools.refresh();
  }
  const client = new ApiClient(req);
  const memoryHistory = createHistory(req.originalUrl);
  const store = createStore(memoryHistory, client);
  const history = syncHistoryWithStore(memoryHistory, store);

  function hydrateOnClient() {
    res.send('<!doctype html>\n' +
      ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>));
  }

  if (__DISABLE_SSR__) {
    hydrateOnClient();
    return;
  }

  match({ history, routes: getRoutes(store), location: req.originalUrl }, (error, redirectLocation, renderProps) => {
    if (redirectLocation) {
      res.redirect(redirectLocation.pathname + redirectLocation.search);
    } else if (error) {
      console.error('ROUTER ERROR:', pretty.render(error));
      res.status(500);
      hydrateOnClient();
    } else if (renderProps) {
      loadOnServer({...renderProps, store, helpers: {client}}).then(() => {
        const component = (
          <Provider store={store} key="provider">
            <ReduxAsyncConnect {...renderProps} />
          </Provider>
        );

        res.status(200);

        global.navigator = {userAgent: req.headers['user-agent']};

        res.send('<!doctype html>\n' +
          ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>));
      });
    } else {
      res.status(404).send('Not found');
    }
  });
});

if (config.port) {
  server.listen(config.port, (err) => {
    if (err) {
      console.error(err);
    }
    console.info('==> 💻  Open http://%s:%s in a browser to view the app.', config.host, config.port);
  });
} else {
  console.error('==>     ERROR: No PORT environment variable has been specified');
}
<|endoftext|>


<commit_before>var _ = require('underscore'),
  async = require('async'),
  fs = require('fs'),
  nano = require('nano');

function Db(url) {

  var couch = nano(url);

  // set up CouchDB databases
  // - display already existing databases
  // - create inexisting databases
  function setDatabases(names, cb) {
    console.log('Preparing databases');

    couch.db.list(function (err, result) {

      if (err) {
        cb(err);

      } else {

        var exist = _.intersection(names, result),
          toCreate = _.difference(names, result);

        // log existing database names
        if (!_.isEmpty(exist)) {
          console.log('- databases already exist: ' + exist);
        }

        // nothing to create
        if (!_.isEmpty(toCreate)) {
          cb(null, exist);

        // create inexisting databases
        } else {
          var tasks = {};
          toCreate.forEach(function (item) {
            tasks[item] = function (cb) {
              console.log('- creating database: ' + item);
              couch.db.create(item, cb);
            };
          });
          async.series(tasks, cb);
        }
      }
    });
  }

  // set up CouchDB documents
  // - create new documents
  // - update existing documents (revision number will be changed afterward)
  function setDocuments(dbDocs, cb) {
    console.log('Preparing documents');

    // prepare only the valid documents
    function _prepareDocs(arr) {
      var docs = [];

      arr.forEach(function (item) {
        if (typeof item === 'string') {
          // TODO construct document either with require or json parse
          try {
            docs.push(JSON.parse(fs.readFileSync(item)));
          } catch (e) {
            console.error('- ignoring invalid document file ' + item + ', error: ' + e.message);
          }
        } else if (typeof item === 'object') {
          docs.push(item);
        } else {
          console.warn('- ignoring invalid document: ' + doc + ', for having type ' + (typeof doc));
        }
      });

      // filter out documents without _id property
      docs = _.filter(docs, function (item) {
        if (_.isEmpty(item._id)) {
          console.warn('- ignoring invalid document: ' + item + ', for not having _id property');
        }
        return !_.isEmpty(item._id);
      });

      return docs;
    }

    // convert result rows array to documents map for easy lookup
    function _rows2Map(rows) {
      var map = {},
        rows = rows || [];
      rows.forEach(function (row) {
        map[row.key] = row.doc;
      });
      return map;
    }

    var tasks = {};
    _.keys(dbDocs).forEach(function (db) {
      tasks[db] = function (cb) {

        var docs = _prepareDocs(dbDocs[db]);
        couch.use(db).fetch({ doc_names: _.pluck(docs, '_id') }, {}, function (err, result) {
          var existingDocs = _rows2Map(result.rows);

          // set revision of already existing documents
          docs.forEach(function (doc) {
            if (existingDocs[doc._id]) {
              doc._rev = existingDocs[doc._id]._rev;
            }
          });

          var toCreate = _.pluck(_.filter(docs, function(item) { return _.isEmpty(item._id); }), '_id'),
            toUpdate = _.pluck(_.filter(docs, function(item) { return !_.isEmpty(item._id); }), '_id');

          // log document IDs to create/update
          if (!_.isEmpty(toCreate)) {
            console.log('- creating documents: ' + toCreate + ' - in database: ' + db);
          }
          if (!_.isEmpty(toUpdate)) {
            console.log('- updating documents: ' + toUpdate + ' - in database: ' + db);
          }

          couch.use(db).bulk({ docs: docs }, {}, cb);
        });
      };
    });
    async.series(tasks, cb);
  }

  return {
    setDatabases: setDatabases,
    setDocuments: setDocuments
  };
}

exports.Db = Db;<commit_msg>Handle undefined rows.<commit_after>var _ = require('underscore'),
  async = require('async'),
  fs = require('fs'),
  nano = require('nano');

function Db(url) {

  var couch = nano(url);

  // set up CouchDB databases
  // - display already existing databases
  // - create inexisting databases
  function setDatabases(names, cb) {
    console.log('Preparing databases');

    couch.db.list(function (err, result) {

      if (err) {
        cb(err);

      } else {

        var exist = _.intersection(names, result),
          toCreate = _.difference(names, result);

        // log existing database names
        if (!_.isEmpty(exist)) {
          console.log('- databases already exist: ' + exist);
        }

        // nothing to create
        if (!_.isEmpty(toCreate)) {
          cb(null, exist);

        // create inexisting databases
        } else {
          var tasks = {};
          toCreate.forEach(function (item) {
            tasks[item] = function (cb) {
              console.log('- creating database: ' + item);
              couch.db.create(item, cb);
            };
          });
          async.series(tasks, cb);
        }
      }
    });
  }

  // set up CouchDB documents
  // - create new documents
  // - update existing documents (revision number will be changed afterward)
  function setDocuments(dbDocs, cb) {
    console.log('Preparing documents');

    // prepare only the valid documents
    function _prepareDocs(arr) {
      var docs = [];

      arr.forEach(function (item) {
        if (typeof item === 'string') {
          // TODO construct document either with require or json parse
          try {
            docs.push(JSON.parse(fs.readFileSync(item)));
          } catch (e) {
            console.error('- ignoring invalid document file ' + item + ', error: ' + e.message);
          }
        } else if (typeof item === 'object') {
          docs.push(item);
        } else {
          console.warn('- ignoring invalid document: ' + doc + ', for having type ' + (typeof doc));
        }
      });

      // filter out documents without _id property
      docs = _.filter(docs, function (item) {
        if (_.isEmpty(item._id)) {
          console.warn('- ignoring invalid document: ' + item + ', for not having _id property');
        }
        return !_.isEmpty(item._id);
      });

      return docs;
    }

    // convert result rows array to documents map for easy lookup
    function _rows2Map(rows) {
      var map = {};
      rows = rows || [];

      rows.forEach(function (row) {
        map[row.key] = row.doc;
      });
      return map;
    }

    var tasks = {};
    _.keys(dbDocs).forEach(function (db) {
      tasks[db] = function (cb) {

        var docs = _prepareDocs(dbDocs[db]);
        couch.use(db).fetch({ doc_names: _.pluck(docs, '_id') }, {}, function (err, result) {
          var existingDocs = _rows2Map(result.rows);

          // set revision of already existing documents
          docs.forEach(function (doc) {
            if (existingDocs[doc._id]) {
              doc._rev = existingDocs[doc._id]._rev;
            }
          });

          var toCreate = _.pluck(_.filter(docs, function(item) { return _.isEmpty(item._id); }), '_id'),
            toUpdate = _.pluck(_.filter(docs, function(item) { return !_.isEmpty(item._id); }), '_id');

          // log document IDs to create/update
          if (!_.isEmpty(toCreate)) {
            console.log('- creating documents: ' + toCreate + ' - in database: ' + db);
          }
          if (!_.isEmpty(toUpdate)) {
            console.log('- updating documents: ' + toUpdate + ' - in database: ' + db);
          }

          couch.use(db).bulk({ docs: docs }, {}, cb);
        });
      };
    });
    async.series(tasks, cb);
  }

  return {
    setDatabases: setDatabases,
    setDocuments: setDocuments
  };
}

exports.Db = Db;<|endoftext|>


<commit_before>'use strict'

const WebSocket = require('ws').Server
const Streamlet = require('streamlet')

module.exports = function Dialup(options) {
	const sockets = {}
  const rooms = {}
  const controller = Streamlet.control()
	const stream = controller.stream
	const ws = new WebSocket(options)

	this.onJoin = stream.filter(message => message.type === 'join')
	this.onOffer = stream.filter(message => message.type === 'offer')
	this.onAnswer = stream.filter(message => message.type === 'answer')
	this.onCandidate = stream.filter(message => message.type === 'candidate')

	this.onJoin.listen(function (message) {
		const socket = message._socket

		if (rooms[message.room] == null) {
			rooms[message.room] = []
		}

		rooms[message.room].forEach(function (client) {
			sockets[client].send(JSON.stringify({
				type: 'new',
				id: socket.hashCode
			}))
		})

		socket.send(JSON.stringify({
			type: 'peers',
			connections: rooms[message.room],
			you: socket.hashCode
		}))

		rooms[message.room].push(socket.hashCode)
	})

	this.onOffer.listen(relay)

	this.onAnswer.listen(relay)

	this.onCandidate.listen(relay)

	function relay(message) {
		const from = message._socket
		const socket = sockets[message.id]

		delete message._socket

		socket.send(JSON.stringify({
			...message,
			id: from.hashCode
		}))
	}

	ws.on('connection', function (socket) {
		socket.hashCode = Math.random().toString(36).slice(2)

		sockets[socket.hashCode] = socket

		socket.on('message', function (message) {
			message = JSON.parse(message)
			message._socket = socket
			controller.add(message)
		})

		socket.on('close', function () {
			const id = socket.hashCode
			delete sockets[id]

			for (const room in rooms) {
				const clients = rooms[room]
				if (clients.indexOf(id) !== -1) {
					clients.splice(clients.indexOf(id), 1)

					clients.forEach(function (client) {
						sockets[client].send(JSON.stringify({
							type: 'leave',
							id: id
						}))
					})
				}
			}
		})
	})
}
<commit_msg>refactor<commit_after>'use strict'

const WebSocketServer = require('ws').Server
const Streamlet = require('streamlet')

module.exports = function Dialup(options) {
	const sockets = {}
  const rooms = {}
  const controller = Streamlet.control()
	const stream = controller.stream
	const wss = new WebSocketServer(options)

	this.onJoin = stream.filter(message => message.type === 'join')
	this.onOffer = stream.filter(message => message.type === 'offer')
	this.onAnswer = stream.filter(message => message.type === 'answer')
	this.onCandidate = stream.filter(message => message.type === 'candidate')

	this.onJoin.listen(function (message) {
		const socket = message.origin

		if (rooms[message.room] == null) {
			rooms[message.room] = []
		}

		rooms[message.room].forEach(function (client) {
			sockets[client].send(JSON.stringify({
				type: 'new',
				id: socket.clientId
			}))
		})

		socket.send(JSON.stringify({
			type: 'peers',
			connections: rooms[message.room],
			you: socket.clientId
		}))

		rooms[message.room].push(socket.clientId)
	})

	this.onOffer.listen(relay)

	this.onAnswer.listen(relay)

	this.onCandidate.listen(relay)

	function relay(message) {
		const from = message.origin
		const socket = sockets[message.id]

		delete message.origin

		socket.send(JSON.stringify({
			...message,
			id: from.clientId
		}))
	}

	wss.on('connection', function (socket) {
		socket.clientId = Math.random().toString(36).slice(2)

		sockets[socket.clientId] = socket

		socket.on('message', function (message) {
			message = JSON.parse(message)
			message.origin = socket

			controller.add(message)
		})

		socket.on('close', function () {
			const id = socket.clientId
			delete sockets[id]

			for (const room in rooms) {
				const clients = rooms[room]
				if (clients.indexOf(id) !== -1) {
					clients.splice(clients.indexOf(id), 1)

					clients.forEach(function (client) {
						sockets[client].send(JSON.stringify({
							type: 'leave',
							id: id
						}))
					})
				}
			}
		})
	})
}
<|endoftext|>


<commit_before>var mongo = require("mongodb");
var async = require("async");

var db = null;

/*
 * Test and create db catalogs if not exists based on config object.
 */
exports.prepare = function( db_config, end_handler ){

	checkdb();

	var catalogs = db_config.system_catalogs.concat(db_config.user_catalogs);
	async.series(
	[
	function(next){//create system and user collections.
		async.forEach(catalogs,function(catalog_name,next){

			db.collection( catalog_name, function(err, collection){

				if( !collection ){

					db.createCollection( catalog_name, function(err, collection){

						if(err)
							throw err;
						else
							next();
					});
				}else
					next();
			});

		},function(err){

			next(err);
		});
	},
	function(next){//create journal index

		db.collection("events", function(err,collection){

			collection.ensureIndex("ev_data.wid",{unique:false},function(err){
				next(err);
			});
		});
	},
	function(next){//create users index.

		db.collection("users", function(err,collection){

			collection.ensureIndex("uid",{unique:false},function(err){
				next(err);
			});
		});
	}
	],function(err){

		end_handler(err, catalogs);
	});

}

/*
 * Close connection to db
 */
exports.close = function(){

	db && db.close();
	db = null;
}

/*
 * Connect to db before any other db operation.
 */
exports.connect = function( params, ret_handler ){

	if( db ){

		db.close();
	}

	params = params || {};
	params.dbhost = params.dbhost || "localhost";
	params.dbport = params.dbport || 27017;
	params.dbname = params.dbname || "jsa";

	db = new mongo.Db(params.dbname, new mongo.Server(params.dbhost,params.dbport,{auto_reconnect:true, socketOptions:{timeout:5000}}),{strict:true, safe:true}); //,poolSize:5,socketOptions:{timeout:1}

	db.open( function(err, client){

		if(client){
			if( params.dbuser !== undefined && params.dbpass !== undefined ){

				db.authenticate(params.dbuser,params.dbpass,function(err,client){

					if(client){
						console.log('**MongoDb driver auth-connected');
						if(ret_handler)
							ret_handler(null,1);
					}else{

						db = null;
						if(ret_handler)
							ret_handler(err,0);
					}
				});
			}else{
				if(ret_handler)
					ret_handler(null,1);
			}
		}else{

			db = null;
			if(ret_handler)
				ret_handler(err,0);
		}

	});

}

/*
 * Check db availability before any db operation.
 */
function checkdb(){

	if( !db )
		throw new Error("Driver not connected, should call connect first.");
}

/*
 * Save object to db.
 *
 */
var save = exports.save = function( col_name, obj, ret_handler ){

    checkdb();

	db.collection(col_name, function(err, collection){

	    collection.save( obj, {safe:true}, function(err, val){

			if( !err )
			    	ret_handler( null, val);
			else
				ret_handler(err,null);
	    });
	});

}

/*
 * Retrieve object from db by ID.
 *
 */
var select = exports.select = function( col_name, id_str, ret_handler ){

    checkdb();

	db.collection( col_name, function(err, collection){

		if(err){

			ret_handler(err,null);
			return;
		}

	    var ObjectID = require('mongodb').ObjectID;
	    collection.findOne({_id:new ObjectID(id_str)},function(err, object){

			if( !err )
			    ret_handler( null,object );
			else
				ret_handler(err,null);
	    });
	});

}

/*
 * Funcion para seleccionar documentos de la bbdd.
 */
var criteria = exports.criteria = function( col_name, criteria, order_field, ret_handler ){

  	checkdb();

	db.collection( col_name, function(err, collection){

    	collection.find(criteria,{}).sort(order_field).toArray(function(err, objects){

			if(!err)
				ret_handler(null,objects);
			else
				ret_handler( err, null );
		});

	});
}

/*
 * Remove object from db by ID.
 */
var removeById = exports.removeById = function( col_name, id_str, ret_handler){

	checkdb();

	db.collection( col_name, function(err, collection){

		if(err){

			ret_handler(err,null);
			return;
		}

	    var ObjectID = require('mongodb').ObjectID;
	    collection.remove( {_id:new ObjectID(id_str)} ,{safe:true},function(err, n){

			if( ret_handler )
				if( !err )
				    ret_handler( null, n );
			    else
			    	ret_handler(err,null);
	    });
	});

}

/*
 * Remove object from db by criteria.
 */
var remove = exports.remove = function( col_name, criteria, ret_handler){

	checkdb();

	db.collection( col_name, function(err, collection){

		if(err){

			ret_handler(err,null);
			return;
		}

	    collection.remove( criteria ,{safe:true},function(err, n){//n: number of rows/docs removed

			if( ret_handler )
				if( !err )
				    ret_handler( null, n );
			    else
			    	ret_handler(err,null);
	    });
	});

}

/*
 * Remove expired document from db, its events and timer.
 */
var remove_global = exports.remove_global = function( col_name, id_str, ret_handler ){

	async.parallel([
		function( end_handler ){//remove doc by id

			removeById(col_name, id_str, function(err){

				end_handler(err);
			});
		},
		function( end_handler ){//remove  events related to doc id

			remove("events",{"ev_msg.ev_data.wid":id_str}, function(err,n){

				end_handler(err);
			});
		}
	], function(err,results){

		if(err)
			throw err;
		else
			ret_handler(null,1);
	});

}

<commit_msg>changes in remove_global to remove all data about a particular doc: journal, users wids list, document iself.<commit_after>var mongo = require("mongodb");
var async = require("async");

var db = null;

/*
 * Test and create db catalogs if not exists based on config object.
 */
exports.prepare = function( db_config, end_handler ){

	checkdb();

	var catalogs = db_config.system_catalogs.concat(db_config.user_catalogs);
	async.series(
	[
	function(next){//create system and user collections.
		async.forEach(catalogs,function(catalog_name,next){

			db.collection( catalog_name, function(err, collection){

				if( !collection ){

					db.createCollection( catalog_name, function(err, collection){

						if(err)
							throw err;
						else
							next();
					});
				}else
					next();
			});

		},function(err){

			next(err);
		});
	},
	function(next){//create journal index

		db.collection("events", function(err,collection){

			collection.ensureIndex("ev_data.wid",{unique:false},function(err){
				next(err);
			});
		});
	},
	function(next){//create users index.

		db.collection("users", function(err,collection){

			collection.ensureIndex("uid",{unique:false},function(err){
				next(err);
			});
		});
	}
	],function(err){

		end_handler(err, catalogs);
	});

}

/*
 * Close connection to db
 */
exports.close = function(){

	db && db.close();
	db = null;
}

/*
 * Connect to db before any other db operation.
 */
exports.connect = function( params, ret_handler ){

	if( db ){

		db.close();
	}

	params = params || {};
	params.dbhost = params.dbhost || "localhost";
	params.dbport = params.dbport || 27017;
	params.dbname = params.dbname || "jsa";

	db = new mongo.Db(params.dbname, new mongo.Server(params.dbhost,params.dbport,{auto_reconnect:true, socketOptions:{timeout:5000}}),{strict:true, safe:true}); //,poolSize:5,socketOptions:{timeout:1}

	db.open( function(err, client){

		if(client){
			if( params.dbuser !== undefined && params.dbpass !== undefined ){

				db.authenticate(params.dbuser,params.dbpass,function(err,client){

					if(client){
						console.log('**MongoDb driver auth-connected');
						if(ret_handler)
							ret_handler(null,1);
					}else{

						db = null;
						if(ret_handler)
							ret_handler(err,0);
					}
				});
			}else{
				if(ret_handler)
					ret_handler(null,1);
			}
		}else{

			db = null;
			if(ret_handler)
				ret_handler(err,0);
		}

	});

}

/*
 * Check db availability before any db operation.
 */
function checkdb(){

	if( !db )
		throw new Error("Driver not connected, should call connect first.");
}

/*
 * Save object to db.
 *
 */
var save = exports.save = function( col_name, obj, ret_handler ){

    checkdb();

	db.collection(col_name, function(err, collection){

	    collection.save( obj, {safe:true}, function(err, val){

			if( !err )
			    	ret_handler( null, val);
			else
				ret_handler(err,null);
	    });
	});

}

/*
 * Retrieve object from db by ID.
 *
 */
var select = exports.select = function( col_name, id_str, ret_handler ){

    checkdb();

	db.collection( col_name, function(err, collection){

		if(err){

			ret_handler(err,null);
			return;
		}

	    var ObjectID = require('mongodb').ObjectID;
	    collection.findOne({_id:new ObjectID(id_str)},function(err, object){

			if( !err )
			    ret_handler( null,object );
			else
				ret_handler(err,null);
	    });
	});

}

/*
 * Funcion para seleccionar documentos de la bbdd.
 */
var criteria = exports.criteria = function( col_name, criteria, order_field, ret_handler ){

  	checkdb();

	db.collection( col_name, function(err, collection){

    	collection.find(criteria,{}).sort(order_field).toArray(function(err, objects){

			if(!err)
				ret_handler(null,objects);
			else
				ret_handler( err, null );
		});

	});
}

/*
 * Remove object from db by ID.
 */
var removeById = exports.removeById = function( col_name, id_str, ret_handler){

	checkdb();

	db.collection( col_name, function(err, collection){

		if(err){

			ret_handler(err,null);
			return;
		}

	    var ObjectID = require('mongodb').ObjectID;
	    collection.remove( {_id:new ObjectID(id_str)} ,{safe:true},function(err, n){

			if( ret_handler )
				if( !err )
				    ret_handler( null, n );
			    else
			    	ret_handler(err,null);
	    });
	});

}

/*
 * Remove object from db by criteria.
 */
var remove = exports.remove = function( col_name, criteria, ret_handler){

	checkdb();

	db.collection( col_name, function(err, collection){

		if(err){

			ret_handler(err,null);
			return;
		}

	    collection.remove( criteria ,{safe:true},function(err, n){//n: number of rows/docs removed

			if( ret_handler )
				if( !err )
				    ret_handler( null, n );
			    else
			    	ret_handler(err,null);
	    });
	});

}

/*
 * Remove expired document from db, its events and timer.
 */
var remove_global = exports.remove_global = function( col_name, id_str, ret_handler ){

	async.series([
		function(end_handler){

			var rcpts;
			async.series([
				function(next){

					select(col_name, id_str,function(err,doc){

						if(err)
							next(err);
						else{
							rcpts = doc.rcpts;
							next();
						}

					});
				},function(next){

					async.forEach(rcpts, function(rcpt,next){

						criteria("users",{uid:rcpt},{},function(err,users){

							var user = users[0];
							var index = user.wids.indexOf(id_str);
							if(index != -1){
								user.wids.splice(index,1);
								save("users",user,function(err){next(err);});
							}else
								next();
						});
					},function(err){

						next(err);
					});
				}
			],function(err){

				end_handler(err);
			});

		},
		function( end_handler ){//remove doc by id

			removeById(col_name, id_str, function(err){

				end_handler(err);
			});
		},
		function( end_handler ){//remove  events related to doc id

			remove("events",{"ev_data.wid":id_str}, function(err,n){

				end_handler(err);
			});
		}
	], function(err,results){

		if(err)
			throw err;
		else
			ret_handler(null,1);
	});

}

<|endoftext|>


<commit_before>/* eslint-disable no-console */
const env = process.env.NODE_ENV || 'development';

import fs from 'fs';
import path from 'path';
import async from 'async';
import nconf from 'nconf';
import etag from 'etag';
import Cron from 'cron';
import mobxstore from 'mobx-store';

// Hapi server imports
import Hapi from 'hapi';
import Inert from 'inert';
import h2o2 from 'h2o2';
import hapiRouter from 'hapi-router';
import AuthBearer from 'hapi-auth-bearer-token';
import cookieJwt from 'hapi-auth-cookie-jwt';

// React imports
import React from 'react';
import ReactDOM from 'react-dom/server';
import { RouterContext, match } from 'react-router';
import { Provider } from 'mobx-react';

// React-router routes and history imports
import Db from '../src/stores/db';
import Stores from './stores';
import createRoutes from '../src/routes';
import api from '../src/lib/server';
import utils from '../src/lib/utils';
import parseCookies from '../src/lib/parseCookies';
import createLocation from 'history/lib/createLocation';
import { createClient } from './lib/redisClient';
import { NotAuthorizedException, RedirectException } from './lib/errors';

let subClient;
let cert;
const CronJob = Cron.CronJob;
const getToken = (headers) => {
  let parts;
  let jwt = null;
  const authorization = headers.authorization;
  const cookie = parseCookies(headers, 'accessToken');
  if (authorization) {
    parts = authorization.split(/\s+/);
  }
  if (cookie) {
    jwt = cookie;
  } else if (parts) {
    jwt = parts[1];
  }

  return jwt;
}
const pushResults = function (message, result) {
  console.log('pushResults', message, result);
  const update = {
    type: message.type,
    collection: message.collection,
    prior: message.target,
    record: result,
    error: result.error,
  };
  utils.pushMessage(`changes.${message.type}`, update);
};
const setSubscription = function () {
  subClient.psubscribe('evangelize:*');
  // console.log("Subscribing");
  subClient.on('pmessage', (pattern, channel, message) => {
    const subChannel = channel.split(':')[1];
    console.log("channel ", channel, ": ", message);
    if (subChannel === 'insert' || subChannel === 'update' || subChannel === 'delete'){
      message = JSON.parse(message);
      const entityId = message.record.entityId;
      const record = message.record;
      console.log('pmessage', message);
      switch (message.type) {
      case 'insert':
        api[message.collection].insert(record)
        .then(
          (results) => {
            results.error = false;
            results.entityId = entityId;
            pushResults(message, results);
          },
          (err) => {
            pushResults(message, err);
          }
        );
        break;
      case 'update':
        api[message.collection].update(record)
        .then(
          (results) => {
            results.error = false;
            results.entityId = entityId;
            pushResults(message, results);
          },
          (err) => {
            pushResults(message, err);
          }
        );
        break;
      case 'delete':
        api[message.collection].delete(record)
        .then(
          (results) => {
            results.error = false;
            results.entityId = entityId;
            pushResults(message, results);
          },
          (err) => {
            pushResults(message, err);
          }
        );
        break;
      default:
        break;
      }
    }
  });
};
const ping = function () {
  subClient.ping((err, res) => {
    console.log('redis server pinged');
  });
};
const startPing = function () {
  new CronJob(
    '05 * * * * *',
    () => {
      ping();
    },
    null,
    true,
    'America/Chicago'
  );
};

createClient().then(
  (client) => {
    subClient = client;
    startPing();
    setSubscription();
  }
);

// Start server function
export default function (HOST, PORT, callback) {
  const plugins = [
    {
      register: Inert,
    },
    {
      register: h2o2,
    },
    {
      register: cookieJwt,
    },
    {
      register: AuthBearer,
    },
  ];
  const settings = nconf.argv()
       .env()
       .file({ file: path.join(__dirname, '../config/settings.json') });
  // console.log("jwtCert", settings.get("jwtCert"));
  cert = fs.readFileSync(settings.get('jwtCert'));
  utils.setCert(cert);
  // console.log("mysql", settings.get("mysql"));
  const server = new Hapi.Server();
  server.connection(
    {
      host: settings.get('host') || HOST,
      port: settings.get('port') || PORT,
    }
  );

  if (env === 'development') {
    const webpack = require('webpack');
    const webpackConfig = require('../webpack/dev.config');
    const WebpackPlugin = require('hapi-webpack-plugin');
    const compiler = webpack(webpackConfig);
    const assets = {
      // webpack-dev-middleware options
      // See https://github.com/webpack/webpack-dev-middleware
      publicPath: '/hot',
      contentBase: 'src',
      stats: {
        colors: true,
        hash: false,
        timings: true,
        chunks: false,
        chunkModules: false,
        modules: false,
      },
    };
    const hot = {
      // webpack-hot-middleware options
      // See https://github.com/glenjamin/webpack-hot-middleware
      timeout: '20000',
      reload: false,
    };
    plugins.push({
      register: WebpackPlugin,
      options: { compiler, assets, hot },
    });
  }
  // Register Hapi plugins
  server.register(
    plugins,
    (error) => {
      if (error) {
        return console.error(error);
      }
      server.auth.strategy(
        'authBearer',
        'bearer-access-token',
        false,
        {
          validateFunc: utils.validateJwt,
        }
      );
      server.auth.strategy(
        'accessToken',
        'jwt-cookie',
        false,
        {
          key: cert,
          validateFunc: utils.validateJwt,
        }
      );

      server.register(
        {
          register: hapiRouter,
          options: {
            routes: 'routes/**/*.js', // uses glob to include files
          },
        },
        (error1) => {
          if (error1) {
            return console.error(error1);
          }
          /**
          * Attempt to serve static requests from the public folder.
          */

          server.ext('onPreResponse', (request, reply) => {
            const cookie = getToken(request.headers);
            const location = createLocation(request.path);
            const stores = new Stores();
            const entityId = request.headers('X-Entity-Id') || null;
            let authenticated = false;
            const retFunc = function (data, person) {
              const newData = Object.assign({}, data);
              const finalDb = JSON.stringify(newData);
              const store = mobxstore(newData);
              const finalMobx = JSON.stringify(store.object);
              const db = new Db();
              let routes;
              let context;
              console.log('init db');
              db.init(data);
              process.nextTick(() => {
                stores.init(db, null).then(
                  () => {
                    stores.stores.settings.authenticated = authenticated;
                    stores.stores.settings.user = { person };
                    routes = createRoutes(stores.stores.settings);
                    context = Object.assign(
                      {
                        db,
                        sockets: null,
                      },
                      stores.stores
                    );
                    match({ routes, location }, (err, redirectLocation, renderProps) => {
                      if (err || !renderProps) {
                        // reply("500: " + error.message)
                        reply.continue();
                      } else if (redirectLocation) {
                        reply.redirect(redirectLocation.pathname + redirectLocation.search);
                      } else if (renderProps) {
                        console.log('ReactDOM: begin render to string');
                        const reactString = ReactDOM.renderToString(
                          <Provider {...context}><RouterContext {...renderProps} /></Provider>
                        );
                        console.log('ReactDOM: end render to string');
                        const config = nconf.argv()
                          .env()
                          .file({ file: path.join(__dirname, '../config/settings.json') });
                        const script = process.env.NODE_ENV === 'production' ? '/dist/client.min.js' : '/hot/client.js';
                        const websocketUri = `//${config.get('websocket:host')}:${settings.get('websocket:port')}`;
                        const output = (
                          `<!doctype html>

                              <meta charset="utf-8">
                              <meta name="viewport" content="width=device-width, minimum-scale=1.0">
                              <title>Evangelize</title>
                              <link rel="stylesheet" href="/css/sanitize.css" />
                              <link rel="stylesheet" href="/css/typography.css" />
                              <link rel="stylesheet" href="/chartist/css/chartist.min.css">
                              <link rel="shortcut icon" sizes="16x16 32x32 48x48 64x64 128x128 256x256" href="/favicon.ico">
                              <link href="//fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
                              <link rel="stylesheet" href="//fonts.googleapis.com/icon?family=Material+Icons" />
                              <link rel="stylesheet" href="/css/custom.css" />

${reactString}

                          `
                        );
                        const eTag = etag(output);
                        reply(output).header('cache-control', 'max-age=0, private, must-revalidate').header('etag', eTag);
                      }
                    });
                  }
                );
              });
            };
            const processRequest = (person) => {
              const newPerson = person || null;
              try {
                if (typeof request.response.statusCode !== 'undefined') {
                  return reply.continue();
                }

                if (!authenticated && request.path !== '/login') {
                  console.log(request.headers);
                  throw new NotAuthorizedException('/login');
                } else if (authenticated && request.path === '/login') {
                  console.log('error authenticated already');
                  throw new RedirectException('/dashboard');
                }

                console.log('Create Window Object');
                if (typeof window === 'undefined'){
                  global.window = Object();
                }

                const { headers } = request;

                global.navigator = {
                  userAgent: headers['user-agent'],
                };

                utils
                .getAllTables()
                .then(
                  (results) => {
                    console.log('got all tables');
                    retFunc(results, newPerson);
                  },
                  (err) => {
                    console.log('error getting all tables', err);
                    retFunc(null, newPerson);
                  }
                );
              } catch (err) {
                if (err instanceof NotAuthorizedException) {
                  console.log('redirect to login');
                  console.error(err);
                  reply.redirect('/login');
                } else if (err instanceof RedirectException) {
                  console.log('redirect to dashboard');
                  reply.redirect('/dashboard');
                }
              }
              return true;
            };
            if (cookie) {
              // console.log("cookie", cookie);
              utils.validateJwt(
                cookie,
                (errors, authorized, credentials) => {
                  if (authorized) {
                    authenticated = true;
                    processRequest(credentials);
                  } else {
                    processRequest();
                  }
                }
              );
            } else {
              processRequest();
            }
          });
          return true;
        }
      );
    }
  );
  // Start Development Server
  return server.start(() => callback(server));
}

process.on('uncaughtException', (err) => {
  const date = new Date();
  console.error(`${date.toUTCString()} uncaughtException:`, err.message);
  console.error(err.stack);
  process.exit(1);
});<commit_msg>access as object<commit_after>/* eslint-disable no-console */
const env = process.env.NODE_ENV || 'development';

import fs from 'fs';
import path from 'path';
import async from 'async';
import nconf from 'nconf';
import etag from 'etag';
import Cron from 'cron';
import mobxstore from 'mobx-store';

// Hapi server imports
import Hapi from 'hapi';
import Inert from 'inert';
import h2o2 from 'h2o2';
import hapiRouter from 'hapi-router';
import AuthBearer from 'hapi-auth-bearer-token';
import cookieJwt from 'hapi-auth-cookie-jwt';

// React imports
import React from 'react';
import ReactDOM from 'react-dom/server';
import { RouterContext, match } from 'react-router';
import { Provider } from 'mobx-react';

// React-router routes and history imports
import Db from '../src/stores/db';
import Stores from './stores';
import createRoutes from '../src/routes';
import api from '../src/lib/server';
import utils from '../src/lib/utils';
import parseCookies from '../src/lib/parseCookies';
import createLocation from 'history/lib/createLocation';
import { createClient } from './lib/redisClient';
import { NotAuthorizedException, RedirectException } from './lib/errors';

let subClient;
let cert;
const CronJob = Cron.CronJob;
const getToken = (headers) => {
  let parts;
  let jwt = null;
  const authorization = headers.authorization;
  const cookie = parseCookies(headers, 'accessToken');
  if (authorization) {
    parts = authorization.split(/\s+/);
  }
  if (cookie) {
    jwt = cookie;
  } else if (parts) {
    jwt = parts[1];
  }

  return jwt;
}
const pushResults = function (message, result) {
  console.log('pushResults', message, result);
  const update = {
    type: message.type,
    collection: message.collection,
    prior: message.target,
    record: result,
    error: result.error,
  };
  utils.pushMessage(`changes.${message.type}`, update);
};
const setSubscription = function () {
  subClient.psubscribe('evangelize:*');
  // console.log("Subscribing");
  subClient.on('pmessage', (pattern, channel, message) => {
    const subChannel = channel.split(':')[1];
    console.log("channel ", channel, ": ", message);
    if (subChannel === 'insert' || subChannel === 'update' || subChannel === 'delete'){
      message = JSON.parse(message);
      const entityId = message.record.entityId;
      const record = message.record;
      console.log('pmessage', message);
      switch (message.type) {
      case 'insert':
        api[message.collection].insert(record)
        .then(
          (results) => {
            results.error = false;
            results.entityId = entityId;
            pushResults(message, results);
          },
          (err) => {
            pushResults(message, err);
          }
        );
        break;
      case 'update':
        api[message.collection].update(record)
        .then(
          (results) => {
            results.error = false;
            results.entityId = entityId;
            pushResults(message, results);
          },
          (err) => {
            pushResults(message, err);
          }
        );
        break;
      case 'delete':
        api[message.collection].delete(record)
        .then(
          (results) => {
            results.error = false;
            results.entityId = entityId;
            pushResults(message, results);
          },
          (err) => {
            pushResults(message, err);
          }
        );
        break;
      default:
        break;
      }
    }
  });
};
const ping = function () {
  subClient.ping((err, res) => {
    console.log('redis server pinged');
  });
};
const startPing = function () {
  new CronJob(
    '05 * * * * *',
    () => {
      ping();
    },
    null,
    true,
    'America/Chicago'
  );
};

createClient().then(
  (client) => {
    subClient = client;
    startPing();
    setSubscription();
  }
);

// Start server function
export default function (HOST, PORT, callback) {
  const plugins = [
    {
      register: Inert,
    },
    {
      register: h2o2,
    },
    {
      register: cookieJwt,
    },
    {
      register: AuthBearer,
    },
  ];
  const settings = nconf.argv()
       .env()
       .file({ file: path.join(__dirname, '../config/settings.json') });
  // console.log("jwtCert", settings.get("jwtCert"));
  cert = fs.readFileSync(settings.get('jwtCert'));
  utils.setCert(cert);
  // console.log("mysql", settings.get("mysql"));
  const server = new Hapi.Server();
  server.connection(
    {
      host: settings.get('host') || HOST,
      port: settings.get('port') || PORT,
    }
  );

  if (env === 'development') {
    const webpack = require('webpack');
    const webpackConfig = require('../webpack/dev.config');
    const WebpackPlugin = require('hapi-webpack-plugin');
    const compiler = webpack(webpackConfig);
    const assets = {
      // webpack-dev-middleware options
      // See https://github.com/webpack/webpack-dev-middleware
      publicPath: '/hot',
      contentBase: 'src',
      stats: {
        colors: true,
        hash: false,
        timings: true,
        chunks: false,
        chunkModules: false,
        modules: false,
      },
    };
    const hot = {
      // webpack-hot-middleware options
      // See https://github.com/glenjamin/webpack-hot-middleware
      timeout: '20000',
      reload: false,
    };
    plugins.push({
      register: WebpackPlugin,
      options: { compiler, assets, hot },
    });
  }
  // Register Hapi plugins
  server.register(
    plugins,
    (error) => {
      if (error) {
        return console.error(error);
      }
      server.auth.strategy(
        'authBearer',
        'bearer-access-token',
        false,
        {
          validateFunc: utils.validateJwt,
        }
      );
      server.auth.strategy(
        'accessToken',
        'jwt-cookie',
        false,
        {
          key: cert,
          validateFunc: utils.validateJwt,
        }
      );

      server.register(
        {
          register: hapiRouter,
          options: {
            routes: 'routes/**/*.js', // uses glob to include files
          },
        },
        (error1) => {
          if (error1) {
            return console.error(error1);
          }
          /**
          * Attempt to serve static requests from the public folder.
          */

          server.ext('onPreResponse', (request, reply) => {
            const cookie = getToken(request.headers);
            const location = createLocation(request.path);
            const stores = new Stores();
            const entityId = request.headers['X-Entity-Id'] || null;
            let authenticated = false;
            const retFunc = function (data, person) {
              const newData = Object.assign({}, data);
              const finalDb = JSON.stringify(newData);
              const store = mobxstore(newData);
              const finalMobx = JSON.stringify(store.object);
              const db = new Db();
              let routes;
              let context;
              console.log('init db');
              db.init(data);
              process.nextTick(() => {
                stores.init(db, null).then(
                  () => {
                    stores.stores.settings.authenticated = authenticated;
                    stores.stores.settings.user = { person };
                    routes = createRoutes(stores.stores.settings);
                    context = Object.assign(
                      {
                        db,
                        sockets: null,
                      },
                      stores.stores
                    );
                    match({ routes, location }, (err, redirectLocation, renderProps) => {
                      if (err || !renderProps) {
                        // reply("500: " + error.message)
                        reply.continue();
                      } else if (redirectLocation) {
                        reply.redirect(redirectLocation.pathname + redirectLocation.search);
                      } else if (renderProps) {
                        console.log('ReactDOM: begin render to string');
                        const reactString = ReactDOM.renderToString(
                          <Provider {...context}><RouterContext {...renderProps} /></Provider>
                        );
                        console.log('ReactDOM: end render to string');
                        const config = nconf.argv()
                          .env()
                          .file({ file: path.join(__dirname, '../config/settings.json') });
                        const script = process.env.NODE_ENV === 'production' ? '/dist/client.min.js' : '/hot/client.js';
                        const websocketUri = `//${config.get('websocket:host')}:${settings.get('websocket:port')}`;
                        const output = (
                          `<!doctype html>

                              <meta charset="utf-8">
                              <meta name="viewport" content="width=device-width, minimum-scale=1.0">
                              <title>Evangelize</title>
                              <link rel="stylesheet" href="/css/sanitize.css" />
                              <link rel="stylesheet" href="/css/typography.css" />
                              <link rel="stylesheet" href="/chartist/css/chartist.min.css">
                              <link rel="shortcut icon" sizes="16x16 32x32 48x48 64x64 128x128 256x256" href="/favicon.ico">
                              <link href="//fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
                              <link rel="stylesheet" href="//fonts.googleapis.com/icon?family=Material+Icons" />
                              <link rel="stylesheet" href="/css/custom.css" />

${reactString}

                          `
                        );
                        const eTag = etag(output);
                        reply(output).header('cache-control', 'max-age=0, private, must-revalidate').header('etag', eTag);
                      }
                    });
                  }
                );
              });
            };
            const processRequest = (person) => {
              const newPerson = person || null;
              try {
                if (typeof request.response.statusCode !== 'undefined') {
                  return reply.continue();
                }

                if (!authenticated && request.path !== '/login') {
                  console.log(request.headers);
                  throw new NotAuthorizedException('/login');
                } else if (authenticated && request.path === '/login') {
                  console.log('error authenticated already');
                  throw new RedirectException('/dashboard');
                }

                console.log('Create Window Object');
                if (typeof window === 'undefined'){
                  global.window = Object();
                }

                const { headers } = request;

                global.navigator = {
                  userAgent: headers['user-agent'],
                };

                utils
                .getAllTables()
                .then(
                  (results) => {
                    console.log('got all tables');
                    retFunc(results, newPerson);
                  },
                  (err) => {
                    console.log('error getting all tables', err);
                    retFunc(null, newPerson);
                  }
                );
              } catch (err) {
                if (err instanceof NotAuthorizedException) {
                  console.log('redirect to login');
                  console.error(err);
                  reply.redirect('/login');
                } else if (err instanceof RedirectException) {
                  console.log('redirect to dashboard');
                  reply.redirect('/dashboard');
                }
              }
              return true;
            };
            if (cookie) {
              // console.log("cookie", cookie);
              utils.validateJwt(
                cookie,
                (errors, authorized, credentials) => {
                  if (authorized) {
                    authenticated = true;
                    processRequest(credentials);
                  } else {
                    processRequest();
                  }
                }
              );
            } else {
              processRequest();
            }
          });
          return true;
        }
      );
    }
  );
  // Start Development Server
  return server.start(() => callback(server));
}

process.on('uncaughtException', (err) => {
  const date = new Date();
  console.error(`${date.toUTCString()} uncaughtException:`, err.message);
  console.error(err.stack);
  process.exit(1);
});<|endoftext|>


<commit_before>var mongoose = require('mongoose');

module.exports = function(){
    mongoose.connect('mongodb://localhost/Velociraptr');

    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function callback () {
        console.log('connected to db');
    });
}<commit_msg>Changed DB name to Wibble<commit_after>var mongoose = require('mongoose');

module.exports = function() {
    mongoose.connect('mongodb://localhost/wibble');

    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function callback () {
        console.log('connected to db');
    });
};<|endoftext|>