<commit_before>var player = require('play-sound')()
var greenBean = require('green-bean')
var uname = require('node-uname')
var fs = require('fs')
var gotPi = false

var unameInfo = uname()
console.log(unameInfo)
console.log('Type: ' + typeof (unameInfo))
if (unameInfo.machine) {
  console.log('Machine: ' + unameInfo.machine)
  if (unameInfo.machine.indexOf('x86') === 0) {
    console.log("This is not a pi so we can't update the board.")
  } else {
    console.log('This machine is not x86, so maybe we can update.')
    gotPi = true
  }
} else {
  console.log('No machine info found.')
}

if (gotPi) {
  var gpio = require('rpi-gpio')

  gpio.on('change', function (channel, value) {
    // When the button is released
    if (value === false) {
      if (chime > Object.keys(chimes).length - 1) {
        chime = 1
      } else {
        chime++
      }
    }
    console.log('chime: ' + chime)
  })
  gpio.setup(7, gpio.DIR_IN, gpio.EDGE_BOTH)
}

var chime = 1
var chimes = {
  1: 'chime',
  2: 'chime_big_ben',
  3: 'chime_x'
}

var codes = {
  1: 'basket_clean',
  2: 'rinse_and_spin',
  3: 'quick_rinse',
  4: 'bulky_items',
  5: 'sanitize',
  6: 'towels_and_sheets',
  7: 'steam_refresh',
  8: 'normal',
  9: 'whites',
  10: 'darks',
  11: 'jeans',
  12: 'hand_wash',
  13: 'delicates',
  14: 'speed_wash',
  15: 'heavy_duty',
  16: 'allergen',
  17: 'power_clean',
  18: 'rinse_and_spin',
  19: 'single_item',
  128: 'cottons',
  129: 'easy_care',
  130: 'active_wear',
  131: 'time_dry',
  132: 'dewrinkle',
  133: 'quick_air_fluff',
  134: 'steam_refresh',
  135: 'steam_dewrinkle',
  136: 'speed_dry',
  137: 'mixed',
  138: 'speed_dry',
  139: 'casuals',
  140: 'warm_up'
}

// All supported languages
var languages = {
  1: 'en',
  2: 'cn',
  3: 'es'
}
// Current language
var language = languages[1]

console.log('test')
greenBean.connect('laundry', function (laundry) {
  console.log('Connected to some laundries')
  var oldSelection = -10

  function requestCycleStatus (callback) {
    laundry.cycleSelected.read(function (value) {
      // Value parameter is the code returned by the washer describing the cycle selected
      if (value === 0 || codes[value] === undefined) {
        console.error('Selection is Undefined or unknown: ' + value)
      } else {
        console.log('New selection : ' + value + ', which is ' + codes[value])
        if (value === oldSelection) {
          console.log('The selection did not change.')
          return
        }
        oldSelection = value
        console.log('Playing a sound for the new selection.')
        playCycleCode(value)
      }
    })
  }

  setInterval(function () {
    console.log('Requesting cycle status.')
    requestCycleStatus()
  }, 1000)

  setInterval(function () {
    laundry.endOfCycle.read(function (value) {
      if (value === 1) {
        console.log('end of cycle')
        playBuzzer()
      } else {
        console.log('not end of cycle')
      }
    })
  }, 60000)
})

function playBuzzer () {
  player.play('buzzers/' + chimes[chime] + '.wav')
}

function playCycleCode (code) {
  var soundFile = './voices/' + language + '/' + codes[code] + '.mp3'
  if (fs.existsSync(soundFile)) {
    player.play(soundFile)
  } else {
    console.log('Sound file does not exist: ' + soundFile)
  }
}
<commit_msg>New cycle selected talking washer functionality<commit_after>var player = require('play-sound')()
var greenBean = require('green-bean')
var uname = require('node-uname')
var fs = require('fs')
var gotPi = false

var unameInfo = uname()
console.log(unameInfo)
console.log('Type: ' + typeof (unameInfo))
if (unameInfo.machine) {
  console.log('Machine: ' + unameInfo.machine)
  if (unameInfo.machine.indexOf('x86') === 0) {
    console.log("This is not a pi so we can't update the board.")
  } else {
    console.log('This machine is not x86, so maybe we can update.')
    gotPi = true
  }
} else {
  console.log('No machine info found.')
}

if (gotPi) {
  var gpio = require('rpi-gpio')

  gpio.on('change', function (channel, value) {
    // When the button is released
    if (value === false) {
      if (chime > Object.keys(chimes).length - 1) {
        chime = 1
      } else {
        chime++
      }
    }
    console.log('chime: ' + chime)
  })
  gpio.setup(7, gpio.DIR_IN, gpio.EDGE_BOTH)
}

var chime = 1
var chimes = {
  1: 'chime',
  2: 'chime_big_ben',
  3: 'chime_x'
}

var codes = {
  1: 'basket_clean',
  2: 'rinse_and_spin',
  3: 'quick_rinse',
  4: 'bulky_items',
  5: 'sanitize',
  6: 'towels_and_sheets',
  7: 'steam_refresh',
  8: 'normal',
  9: 'whites',
  10: 'darks',
  11: 'jeans',
  12: 'hand_wash',
  13: 'delicates',
  14: 'speed_wash',
  15: 'heavy_duty',
  16: 'allergen',
  17: 'power_clean',
  18: 'rinse_and_spin',
  19: 'single_item',
  128: 'cottons',
  129: 'easy_care',
  130: 'active_wear',
  131: 'time_dry',
  132: 'dewrinkle',
  133: 'quick_air_fluff',
  134: 'steam_refresh',
  135: 'steam_dewrinkle',
  136: 'speed_dry',
  137: 'mixed',
  138: 'speed_dry',
  139: 'casuals',
  140: 'warm_up'
}

// All supported languages
var languages = {
  1: 'en',
  2: 'cn',
  3: 'es'
}
// Current language
var language = languages[1]

console.log('test')
greenBean.connect('laundry', function (laundry) {
  console.log('Connected to some laundries')
  var oldSelection = -10

  function requestCycleSelectedStatus (callback) {
    laundry.cycleSelected.read(function (value) {
      // Value parameter is the code returned by the washer describing the cycle selected
      if (value === 0 || codes[value] === undefined) {
        console.error('Selection is Undefined or unknown: ' + value)
      } else {
        console.log('New selection : ' + value + ', which is ' + codes[value])
        if (value === oldSelection) {
          console.log('The selection did not change.')
          return
        }
        oldSelection = value
        console.log('Playing a sound for the new selection.')
        playCycleCode(value)
      }
    })
  }

  var beepCount = 0
  var isEndOfCycle = false
  function requestEndOfCycleStatus (laundry) {
    laundry.machineStatus.read(function (machineStatus) {
      switch (machineStatus) {
        case 0:
          // Do not remove this case
          break
        case 2:
          isEndOfCycle = false
          console.log('in a cycle')
          break
        case 4:
          isEndOfCycle = true
          console.log('end of cycle')
          break;
        default:
          isEndOfCycle = false
          console.log(machineStatus)
          break
      }
      if (isEndOfCycle && beepCount % 60 === 0) {
        beepCount = 0
        console.log('playing buzzer')
        playBuzzer()
      }
      if (isEndOfCycle) {
        beepCount++
      }
      console.log('beepCount: '+beepCount, ' isEndOfCycle: '+isEndOfCycle)
    });
  }

  setInterval(function () {
    console.log('Requesting cycle status.')
    requestCycleSelectedStatus()
  }, 1000)

  setInterval(function() {
    requestEndOfCycleStatus(laundry)
  } , 1000)
})

function playBuzzer () {
  player.play('buzzers/' + chimes[chime] + '.wav')
}

function playCycleCode (code) {
  var soundFile = './voices/' + language + '/' + codes[code] + '.mp3'
  if (fs.existsSync(soundFile)) {
    player.play(soundFile)
  } else {
    console.log('Sound file does not exist: ' + soundFile)
  }
}
<|endoftext|>


<commit_before>// From https://gist.github.com/epeli/11209665

var Promise = require("bluebird");

// So you can `var request = require("superagent-bluebird-promise")`
var superagent = module.exports = require("superagent");
var Request = superagent.Request;

// Create custom error type.
// Create a new object, that prototypally inherits from the Error constructor.
function SuperagentPromiseError(message) {
  this.name = 'SuperagentPromiseError';
  this.message = message || 'Bad request';
}

SuperagentPromiseError.prototype = new Error();
SuperagentPromiseError.prototype.constructor = SuperagentPromiseError;

/**
 * @namespace utils
 * @class Superagent
 */

/**
 *
 * Add promise support for superagent/supertest
 *
 * Call .promise() to return promise for the request
 *
 * @method promise
 * @return {Bluebird.Promise}
 */
Request.prototype.promise = function() {
  var self = this;
  var error;
  return new Promise(function(resolve, reject) {
      self.end(function(err, res) {
        if (typeof res !== "undefined" && res.status >= 400) {
          var req = res.req;
          var msg = 'cannot ' + req.method + ' ' + req._headers.host + req.path + ' (' + res.status + ')';
          error = new SuperagentPromiseError(msg);
          error.status = res.status;
          error.body = res.body;
          error.res = res;
          reject(error);
        } else if (err) {
          reject(new SuperagentPromiseError(err));
        } else {
          resolve(res);
        }
      });
    });
};
<commit_msg>Modified a error message creation.<commit_after>// From https://gist.github.com/epeli/11209665

var Promise = require("bluebird");

// So you can `var request = require("superagent-bluebird-promise")`
var superagent = module.exports = require("superagent");
var Request = superagent.Request;

// Create custom error type.
// Create a new object, that prototypally inherits from the Error constructor.
function SuperagentPromiseError(message) {
  this.name = 'SuperagentPromiseError';
  this.message = message || 'Bad request';
}

SuperagentPromiseError.prototype = new Error();
SuperagentPromiseError.prototype.constructor = SuperagentPromiseError;

/**
 * @namespace utils
 * @class Superagent
 */

/**
 *
 * Add promise support for superagent/supertest
 *
 * Call .promise() to return promise for the request
 *
 * @method promise
 * @return {Bluebird.Promise}
 */
Request.prototype.promise = function() {
  var req = this;
  var error;
  return new Promise(function(resolve, reject) {
      req.end(function(err, res) {
        if (typeof res !== "undefined" && res.status >= 400) {
          var msg = 'cannot ' + req.method + ' ' + req.url + ' (' + res.status + ')';
          error = new SuperagentPromiseError(msg);
          error.status = res.status;
          error.body = res.body;
          error.res = res;
          reject(error);
        } else if (err) {
          reject(new SuperagentPromiseError(err));
        } else {
          resolve(res);
        }
      });
    });
};
<|endoftext|>


<commit_before>'use strict';

const createAbortError = () => {
	const error = new Error('Delay aborted');
	error.name = 'AbortError';
	return error;
};

const createDelay = ({clearTimeout: defaultClear, setTimeout: set, willResolve}) => (ms, {value, signal} = {}) => {
	if (signal && signal.aborted) {
		return Promise.reject(createAbortError());
	}

	let timeoutId;
	let settle;
	let rejectFn;
	const clear = defaultClear || clearTimeout;

	const signalListener = () => {
		clear(timeoutId);
		rejectFn(createAbortError());
	};

	const cleanup = () => {
		if (signal) {
			signal.removeEventListener('abort', signalListener);
		}
	};

	const delayPromise = new Promise((resolve, reject) => {
		settle = () => {
			cleanup();
			if (willResolve) {
				resolve(value);
			} else {
				reject(value);
			}
		};

		rejectFn = reject;
		timeoutId = (set || setTimeout)(settle, ms);
	});

	if (signal) {
		signal.addEventListener('abort', signalListener, {once: true});
	}

	delayPromise.clear = () => {
		clear(timeoutId);
		timeoutId = null;
		cleanup();
		settle();
	};

	return delayPromise;
};

const delay = createDelay({willResolve: true});
delay.reject = createDelay({willResolve: false});
delay.createWithTimers = ({clearTimeout, setTimeout}) => {
	const delay = createDelay({clearTimeout, setTimeout, willResolve: true});
	delay.reject = createDelay({clearTimeout, setTimeout, willResolve: false});
	return delay;
};

module.exports = delay;
// TODO: Remove this for the next major release
module.exports.default = delay;
<commit_msg>Remove duplicate `cleanup()` call (#48)<commit_after>'use strict';

const createAbortError = () => {
	const error = new Error('Delay aborted');
	error.name = 'AbortError';
	return error;
};

const createDelay = ({clearTimeout: defaultClear, setTimeout: set, willResolve}) => (ms, {value, signal} = {}) => {
	if (signal && signal.aborted) {
		return Promise.reject(createAbortError());
	}

	let timeoutId;
	let settle;
	let rejectFn;
	const clear = defaultClear || clearTimeout;

	const signalListener = () => {
		clear(timeoutId);
		rejectFn(createAbortError());
	};

	const cleanup = () => {
		if (signal) {
			signal.removeEventListener('abort', signalListener);
		}
	};

	const delayPromise = new Promise((resolve, reject) => {
		settle = () => {
			cleanup();
			if (willResolve) {
				resolve(value);
			} else {
				reject(value);
			}
		};

		rejectFn = reject;
		timeoutId = (set || setTimeout)(settle, ms);
	});

	if (signal) {
		signal.addEventListener('abort', signalListener, {once: true});
	}

	delayPromise.clear = () => {
		clear(timeoutId);
		timeoutId = null;
		settle();
	};

	return delayPromise;
};

const delay = createDelay({willResolve: true});
delay.reject = createDelay({willResolve: false});
delay.createWithTimers = ({clearTimeout, setTimeout}) => {
	const delay = createDelay({clearTimeout, setTimeout, willResolve: true});
	delay.reject = createDelay({clearTimeout, setTimeout, willResolve: false});
	return delay;
};

module.exports = delay;
// TODO: Remove this for the next major release
module.exports.default = delay;
<|endoftext|>


<commit_before>// ------------------------------------
// #POST - LOAD PLUGINS
// ------------------------------------

'use strict';
const path = require('path');

exports = module.exports = function (options) {
	var pkg = require(path.join(process.cwd(), 'package.json'));

	if (typeof options === 'string') {
		options = require(path.join(process.cwd(), options));
	} else {
		options = options || pkg.posthtml || {};
	}

	function Processor(plugin) {
		function namespace(plugin) {
			let namespace = plugin
			.slice(9)
			.replace(/-(\w)/g, (match) => {
				return match.replace(/-/, '').toUpperCase();
			});
			return `${namespace}`;
		}

		return {
			plugin: require(`${plugin}`),
			namespace: namespace(plugin),
			defaults: {}
		};
	}

	function isPlugin(element) {
		return element.match(/posthtml-[\w]/);
	}

	function isInclude(element) {
		return element.match(/posthtml-[include]/);
	}

	function notInclude(element) {
		return element.match(/posthtml-[^include]/);
	}

	var processors = [];

	Object.keys(pkg.dependencies).filter(isPlugin).filter(isInclude).forEach((plugin) => {
		processors.unshift(new Processor(plugin));
	});

	Object.keys(pkg.dependencies).filter(isPlugin).filter(notInclude).forEach((plugin) => {
		processors.push(new Processor(plugin));
	});

	Object.keys(pkg.devDependencies).filter(isPlugin).filter(isInclude).forEach((plugin) => {
		processors.unshift(new Processor(plugin));
	});

	Object.keys(pkg.devDependencies).filter(isPlugin).filter(notInclude).forEach((plugin) => {
		processors.push(new Processor(plugin));
	});

	var plugins = [];

	processors.forEach((processor) => {
		var namespaceOptions = processor.namespace in options ? options[processor.namespace] : options;
		var processorOptions = {};

		Object.keys(processor.defaults).forEach((key) => {
			processorOptions[key] = processor.defaults[key];
		});

		Object.keys(namespaceOptions).forEach((key) => {
			processorOptions[key] = namespaceOptions[key];
		});

		if (namespaceOptions && !processorOptions.disable) {
			plugins.push(processor.plugin(processorOptions));
		}
	});

	return plugins;
};
<commit_msg>Fixed path to root package.json<commit_after>// ------------------------------------
// #POST - LOAD PLUGINS
// ------------------------------------

'use strict';
const path = require('path');

exports = module.exports = function (options) {
	var pkg = require(path.join(process.env.pwd, 'package.json'));

	if (typeof options === 'string') {
		options = require(path.join(process.cwd(), options));
	} else {
		options = options || pkg.posthtml || {};
	}

	function Processor(plugin) {
		function namespace(plugin) {
			let namespace = plugin
			.slice(9)
			.replace(/-(\w)/g, (match) => {
				return match.replace(/-/, '').toUpperCase();
			});
			return `${namespace}`;
		}

		return {
			plugin: require(`${plugin}`),
			namespace: namespace(plugin),
			defaults: {}
		};
	}

	function isPlugin(element) {
		return element.match(/posthtml-[\w]/);
	}

	function isInclude(element) {
		return element.match(/posthtml-[include]/);
	}

	function notInclude(element) {
		return element.match(/posthtml-[^include]/);
	}

	var processors = [];

	Object.keys(pkg.dependencies).filter(isPlugin).filter(isInclude).forEach((plugin) => {
		processors.unshift(new Processor(plugin));
	});

	Object.keys(pkg.dependencies).filter(isPlugin).filter(notInclude).forEach((plugin) => {
		processors.push(new Processor(plugin));
	});

	Object.keys(pkg.devDependencies).filter(isPlugin).filter(isInclude).forEach((plugin) => {
		processors.unshift(new Processor(plugin));
	});

	Object.keys(pkg.devDependencies).filter(isPlugin).filter(notInclude).forEach((plugin) => {
		processors.push(new Processor(plugin));
	});

	var plugins = [];

	processors.forEach((processor) => {
		var namespaceOptions = processor.namespace in options ? options[processor.namespace] : options;
		var processorOptions = {};

		Object.keys(processor.defaults).forEach((key) => {
			processorOptions[key] = processor.defaults[key];
		});

		Object.keys(namespaceOptions).forEach((key) => {
			processorOptions[key] = namespaceOptions[key];
		});

		if (namespaceOptions && !processorOptions.disable) {
			plugins.push(processor.plugin(processorOptions));
		}
	});

	return plugins;
};
<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
    SourceNode = require('source-map').SourceNode,
    SourceMapConsumer = require('source-map').SourceMapConsumer,
    makeIdentitySourceMap = require('./makeIdentitySourceMap');

var REACT_MARKER_RE = /render\s*[=:\(]/g;

module.exports = function (source, map) {
  if (this.cacheable) {
    this.cacheable();
  }

  var resourcePath = this.resourcePath;
  if (!source.match(REACT_MARKER_RE)) {
    return this.callback(null, source, map);
  }

  var acceptUpdates = this.query !== '?manual',
      filename = path.basename(resourcePath),
      separator = '\n\n',
      prependText,
      appendText,
      node,
      result;

  prependText = [
    '/* REACT HOT LOADER */',
    'if (module.hot) {',
      '(function () {',
        'var reactHotApi = require(' + JSON.stringify(require.resolve('react-hot-api')) + '),',
        '    getRootInstances = require(' + JSON.stringify(require.resolve('./getRootInstances')) + ');',
        '',
        'if (typeof reactHotApi === "function" && typeof getRootInstances === "function") {',
          'module.makeHot = module.hot.data ? module.hot.data.makeHot : reactHotApi(getRootInstances);',
        '}',
      '})();',
    '}'
  ].join(' ');

  appendText = [
    '/* REACT HOT LOADER */',
    'if (module.hot) {',
      acceptUpdates ? [
        'module.hot.accept(function (err) {',
          'if (err) {',
            'console.error("Cannot not apply hot update to " + ' + JSON.stringify(filename) + ' + ": " + err.message);',
          '}',
        '});'
      ].join(' ') : '',
      'module.hot.dispose(function (data) {',
      '  data.makeHot = module.makeHot;',
      '});',
      'if (module.exports && module.makeHot) {',
      '  module.exports = module.makeHot(module.exports, "__MODULE_EXPORTS")',
      '}',
    '}'
  ].join(' ');

  if (this.sourceMap === false) {
    return this.callback(null, [
      prependText,
      source,
      appendText
    ].join(separator));
  }

  if (!map) {
    map = makeIdentitySourceMap(source, this.resourcePath);
  }

  node = new SourceNode(null, null, null, [
    new SourceNode(null, null, this.resourcePath, prependText),
    SourceNode.fromStringWithSourceMap(source, new SourceMapConsumer(map)),
    new SourceNode(null, null, this.resourcePath, appendText)
  ]).join(separator);

  result = node.toStringWithSourceMap();

  this.callback(null, result.code, result.map.toString());
};
<commit_msg>Use path check to skip React and Webpack internals<commit_after>'use strict';

var path = require('path'),
    SourceNode = require('source-map').SourceNode,
    SourceMapConsumer = require('source-map').SourceMapConsumer,
    makeIdentitySourceMap = require('./makeIdentitySourceMap');

module.exports = function (source, map) {
  if (this.cacheable) {
    this.cacheable();
  }

  var resourcePath = this.resourcePath;
  if (resourcePath.indexOf('/node_modules/react/') > -1 ||
      resourcePath.indexOf('/node_modules/webpack/') > -1) {
    // Skip internals
    return this.callback(null, source, map);
  }

  var acceptUpdates = this.query !== '?manual',
      filename = path.basename(resourcePath),
      separator = '\n\n',
      prependText,
      appendText,
      node,
      result;

  prependText = [
    '/* REACT HOT LOADER */',
    'if (module.hot) {',
      '(function () {',
        'var reactHotApi = require(' + JSON.stringify(require.resolve('react-hot-api')) + '),',
        '    getRootInstances = require(' + JSON.stringify(require.resolve('./getRootInstances')) + ');',
        '',
        'if (typeof reactHotApi === "function" && typeof getRootInstances === "function") {',
          'module.makeHot = module.hot.data ? module.hot.data.makeHot : reactHotApi(getRootInstances);',
        '}',
      '})();',
    '}'
  ].join(' ');

  appendText = [
    '/* REACT HOT LOADER */',
    'if (module.hot) {',
      acceptUpdates ? [
        'module.hot.accept(function (err) {',
          'if (err) {',
            'console.error("Cannot not apply hot update to " + ' + JSON.stringify(filename) + ' + ": " + err.message);',
          '}',
        '});'
      ].join(' ') : '',
      'module.hot.dispose(function (data) {',
      '  data.makeHot = module.makeHot;',
      '});',
      'if (module.exports && module.makeHot) {',
      '  module.exports = module.makeHot(module.exports, "__MODULE_EXPORTS")',
      '}',
    '}'
  ].join(' ');

  if (this.sourceMap === false) {
    return this.callback(null, [
      prependText,
      source,
      appendText
    ].join(separator));
  }

  if (!map) {
    map = makeIdentitySourceMap(source, this.resourcePath);
  }

  node = new SourceNode(null, null, null, [
    new SourceNode(null, null, this.resourcePath, prependText),
    SourceNode.fromStringWithSourceMap(source, new SourceMapConsumer(map)),
    new SourceNode(null, null, this.resourcePath, appendText)
  ]).join(separator);

  result = node.toStringWithSourceMap();

  this.callback(null, result.code, result.map.toString());
};
<|endoftext|>


<commit_before>var path = require('path');
var findRoot = require('find-root');
var chalk = require('chalk');
var _ = require('lodash');

function DuplicatePackageCheckerPlugin() {}

DuplicatePackageCheckerPlugin.prototype.apply = function(compiler) {
  compiler.plugin('emit', function(compilation, callback) {

    var modules = {};

    compilation.modules.forEach(module => {

      if (!module.resource) {
        return;
      }

      var root = findRoot(module.resource);

      var pkg = require(path.join(root, 'package.json'));

      modules[pkg.name] = (modules[pkg.name] || []);

      if (!_.includes(modules[pkg.name], pkg.version)) {
        modules[pkg.name].push(pkg.version);
      }

    });

    var duplicates = _.omitBy(modules, versions => versions.length <= 1);

    if (Object.keys(duplicates).length) {

      _.each(duplicates, (versions, name) => {
        compilation.warnings.push(new Error('duplicate-package-checker: <' + chalk.green.bold(name) + '> - ' + chalk.yellow.bold(versions.join(', '))));
      });
    }

    callback();
  });
};

module.exports = DuplicatePackageCheckerPlugin;
<commit_msg>Add path in output<commit_after>var path = require('path');
var findRoot = require('find-root');
var chalk = require('chalk');
var _ = require('lodash');

function DuplicatePackageCheckerPlugin() {}

function cleanPath(path) {
  return '.' + path.split('/node_modules/').join('/~/');
}

DuplicatePackageCheckerPlugin.prototype.apply = function(compiler) {
  compiler.plugin('emit', function(compilation, callback) {

    let context = compilation.compiler.context;
    let modules = {};

    compilation.modules.forEach(module => {

      if (!module.resource) {
        return;
      }

      let root = findRoot(module.resource);
      let pkg = require(path.join(root, 'package.json'));

      let modulePath = cleanPath(root.replace(context, ''));
      let version = pkg.version;

      modules[pkg.name] = (modules[pkg.name] || []);

      let isSeen = _.find(modules[pkg.name], module => {
        return module.version === version && module.path === modulePath;
      });

      if (!isSeen) {
        modules[pkg.name].push({ version, path: modulePath });
      }

    });

    let duplicates = _.omitBy(modules, versions => versions.length <= 1);

    if (Object.keys(duplicates).length) {

      let error = 'duplicate-package-checker:';

      _.each(duplicates, (instances, name) => {
        instances = instances.map(version => {
          return `${chalk.green.bold(version.version)} ${chalk.white.bold(version.path)}`;
        });
        error += `\n  ${chalk.yellow.bold('<')}${chalk.green.bold(name)}${chalk.yellow.bold('>')}\n`;
        error += `    ${instances.join('\n    ')}\n`;
      });

      compilation.warnings.push(new Error(error));

    }

    callback();
  });
};

module.exports = DuplicatePackageCheckerPlugin;
<|endoftext|>


<commit_before>var http = require('http');
var express = require('express');
var controllers = require('./controllers');

var app = express();

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));

app.get('/', controllers.home.home);

var server = app.listen(3000, function() {

  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);

});

/*
// 00 second 01 minutes every hours
new CronJob('00 01 * * * *', function() {
  lib.check();
}, null, true);

http.createServer(function(req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  lib.getCache(function(error, cache) {
    var output = '';
    if (error) {
      output = error;
    }
    else {
      output = cache;
    }
    res.end(output);
  });
}).listen(process.env.PORT || 1337, null);
*/
<commit_msg>added new routes<commit_after>var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var controllers = require('./controllers');

var app = express();
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(bodyParser.json());
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));

app.get('/', controllers.home.home);
app.post('/add', controllers.home.add);
app.get('/validate/:token', controllers.home.validate);

var server = app.listen(3000, function() {

  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);

});

/*
// 00 second 01 minutes every hours
new CronJob('00 01 * * * *', function() {
  lib.check();
}, null, true);

http.createServer(function(req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  lib.getCache(function(error, cache) {
    var output = '';
    if (error) {
      output = error;
    }
    else {
      output = cache;
    }
    res.end(output);
  });
}).listen(process.env.PORT || 1337, null);
*/
<|endoftext|>


<commit_before>/**
 * element
 * Element component
 *
 * @author Enrico Marino
 * @copyright 2013 Enrico Marino
 */

/*
 * Expose `create_element`
 */

module.expose = create_element;

/*
 * create_element
 */

function create_element () {

  /*
   * element
   */

  function element (el) {
    if (!(this instanceof element)) {
      return new element(el);
    }
    this.el = el;
  }

  /**
   * use
   *
   * @param {Object} proto
   * @return {element} this for chaining
   * @api public
   */

  element.use = function (proto) {
    var key;
    for (key in proto) {
      element.prototype[key] = proto[key];
    }
    return this;
  };

  return element;
}
<commit_msg>Update element.use<commit_after>/**
 * element
 * Element component
 *
 * @author Enrico Marino
 * @copyright 2013 Enrico Marino
 */

/*
 * Expose `create_element`
 */

module.expose = create_element;

/*
 * create_element
 */

function create_element () {

  /*
   * element
   */

  function element (el) {
    if (!(this instanceof element)) {
      return new element(el);
    }
    this.el =
    this.element = el;
  }

  /**
   * use
   *
   * @param {Object} proto
   * @return {element} this for chaining
   * @api public
   */

  element.use = function (fn) {
    fn(this);
    return this;
  };

  return element;
}
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var event = new EventEmitter();

var eventSpinner = function(config) {
    var config = config || {};
    config.fixed = config.fixed || true;
    this.spinner = config.spinner || 'fa-spinner';
    this.animation = config.animation || 'fa-spin';
    this.size = config.size || 'fa-3x';
    this.fixed = (config.fixed ? 'fa-fw' : '');
    this.rgba = config.rgba || [255, 255, 255, 0.5];
    this.container = config.container || 'app';
    this.z = config.z || 8000;
    this.top = config.top || 50;
    this.left = config.left || 50;

    var divContainer = document.createElement('div');
    var divSpinner = document.createElement('div');
    var spinner = document.createElement('i');

    divContainer.style.display = 'none';
    spinner.className = 'fa ' + this.spinner + ' ' + this.animation + ' ' + this.size + ' ' + this.fixed;
    var vm = this;
    event.addListener('addSpinner', function() {
        divContainer.style.display = '';
        divContainer.style.width= '100%';
        divContainer.style.height= '100%';
        divContainer.style['z-index']= vm.z;
        divContainer.style.top= '0';
        divContainer.style.left= '0';
        divContainer.style['background-color']= 'rgba(' + vm.rgba +')';
        divContainer.style.position= 'absolute';
        divSpinner.style.position= 'fixed';
        divSpinner.style.top = vm.top + '%';
        divSpinner.style.left = vm.left + '%';
        divSpinner.appendChild(spinner);
        divContainer.appendChild(divSpinner);
        var container = document.getElementById(vm.container);
        container.style.position = 'relative';
        container.appendChild(divContainer);
    });

    event.addListener('removeSpinner', function() {
        divContainer.style.display = 'none';
    });
};

eventSpinner.prototype.showSpinner= function() {
  event.emit('addSpinner');
};

eventSpinner.prototype.hideSpinner= function() {
  event.emit('removeSpinner');
};

module.exports = eventSpinner;<commit_msg>style fixes<commit_after>var EventEmitter = require('events').EventEmitter;
var event = new EventEmitter();

var eventSpinner = function (config) {
  var config = config || {};
  config.fixed = config.fixed || true;
  this.spinner = config.spinner || 'fa-spinner';
  this.animation = config.animation || 'fa-spin';
  this.size = config.size || 'fa-3x';
  this.fixed = (config.fixed ? 'fa-fw' : '');
  this.rgba = config.rgba || [255, 255, 255, 0.5];
  this.container = config.container || 'app';
  this.z = config.z || 8000;
  this.top = config.top || 50;
  this.left = config.left || 50;

  var divContainer = document.createElement('div');
  var divSpinner = document.createElement('div');
  var spinner = document.createElement('i');

  divContainer.style.display = 'none';
  spinner.className = 'fa ' + this.spinner + ' ' + this.animation + ' ' + this.size + ' ' + this.fixed;
  var vm = this;
  event.addListener('addSpinner', function () {
    divContainer.style.display = '';
    divContainer.style.width = '100%';
    divContainer.style.height = '100%';
    divContainer.style['z-index'] = vm.z;
    divContainer.style.top = '0';
    divContainer.style.left = '0';
    divContainer.style['background-color'] = 'rgba(' + vm.rgba + ')';
    divContainer.style.position = 'absolute';
    divSpinner.style.position = 'fixed';
    divSpinner.style.top = vm.top + '%';
    divSpinner.style.left = vm.left + '%';
    divSpinner.appendChild(spinner);
    divContainer.appendChild(divSpinner);
    var container = document.getElementById(vm.container);
    container.style.position = 'relative';
    container.appendChild(divContainer);
  });

  event.addListener('removeSpinner', function () {
    divContainer.style.display = 'none';
  });
};

eventSpinner.prototype.showSpinner = function () {
  event.emit('addSpinner');
};

eventSpinner.prototype.hideSpinner = function () {
  event.emit('removeSpinner');
};

module.exports = eventSpinner;<|endoftext|>


<commit_before>var moduleFactory = require('./lib/shared/ModuleFactory.js');
var request = require('./lib/shared/Request.js');
var reply = require('./lib/shared/Reply.js');
var errorHandler = require('./lib/shared/ErrorHandler.js');
var user = require('./lib/shared/User.js');
var fs = require('fs');
// sign with default (HMAC SHA256)
var jwt = require('jsonwebtoken');

// sign with RSA SHA256
var cert = fs.readFileSync('rsa');  // get private key

exports.handler = function(event, context){
    var callingFunction = context.functionName;
    var token = event.sessionToken;

    var req = request(token,event,context);
    var rep = reply(req);
    var err = errorHandler(req);
    //NEED TO LOOKUP IN USERDB FIRST, FIX
    try {
  		var decoded = jwt.verify(token, cert);
	}
	catch(err) {
		//err
		console.log("token invalid");

	}
    var usr = user(decoded.RIN,token);
    var usr = user()

    var module = moduleFactory(callingFunction, usr, req, rep);
    module.run();
};

<commit_msg>added token auth to index<commit_after>var moduleFactory = require('./lib/shared/ModuleFactory.js');
var request = require('./lib/shared/Request.js');
var reply = require('./lib/shared/Reply.js');
var errorHandler = require('./lib/shared/ErrorHandler.js');
var user = require('./lib/shared/User.js');
var fs = require('fs');
// sign with default (HMAC SHA256)
var jwt = require('jsonwebtoken');

// sign with RSA SHA256
var cert = fs.readFileSync('rsa');  // get private key

exports.handler = function(event, context){
    var callingFunction = context.functionName;
    var token = event.sessionToken;

    var req = request(token,event,context);
    var rep = reply(req);
    var err = errorHandler(req);
    //NEED TO LOOKUP IN USERDB FIRST, FIX
    var decoded = {};
    if(typeof token != 'undefined'){
        try {
  		decoded = jwt.verify(token, cert, { algorithms: ['RS256'] });
	   }
    	catch(err) {
		//err
        console.log(err);
		console.log("token invalid");

	   }
    }else{
        decoded.RIN = event.RIN;
    }
    var usr = user(decoded.RIN,token);

    var module = moduleFactory(callingFunction, usr, req, rep);
    module.run();
};

<|endoftext|>


<commit_before>////
//// PasteSafe web app.
////

// Forcing HTTPS in production.
var production = /github\.io/i.test(window.location.href) || /pastesafe\.com/i.test(window.location.href);
if (production && !/https/i.test(window.location.protocol))
    window.location.href = "https:" + window.location.href.substring(window.location.protocol.length);

// Obtaining references to PasteSafe DOM elements.
var root = document.querySelector('[paste-safe]');
var textInput = root.querySelector('textarea.text-input');
var textOutput = root.querySelector('textarea.text-output');
var passwordInput = root.querySelector('input.password');
var encryptButton = root.querySelector('.encrypt');
var decryptButton = root.querySelector('.decrypt');
var outputBlocker = root.querySelector('.output-blocker');
var bottomLink = root.querySelector('.bottom-link');
var getCryptionMode = () => root.querySelector('input[name="cryption_mode"]:checked').value;

// Handling the switch between 'encrypt' and 'decrypt' cryption mode.
function refreshCryptionMode() {
    var cryptionMode = getCryptionMode();
    if (cryptionMode === 'encrypt') {
        root.setAttribute('data-cryption-mode', 'encrypt');
        decryptButton.parentElement.removeAttribute('data-checked');
        encryptButton.parentElement.setAttribute('data-checked', '');
    }
    else {
        root.setAttribute('data-cryption-mode', 'decrypt');
        encryptButton.parentElement.removeAttribute('data-checked');
        decryptButton.parentElement.setAttribute('data-checked', '');
    }
}
encryptButton.addEventListener('change', refreshCryptionMode);
decryptButton.addEventListener('change', refreshCryptionMode);
refreshCryptionMode();

function setCryptionMode(mode) {
    encryptButton.checked = (mode==='encrypt') ?true :false;
    decryptButton.checked = (mode==='decrypt') ?true :false;
    refreshCryptionMode();
}

// Blocking the output textarea with a message.
// Modes:
//  - off: no output blocker.
//  - plain: subtle blocker with a simple message.
//  - error: angry blocker that indicates something went wrong.
function setOutputBlocker(options) {
    var mode = options.mode || "off";
    var list = options.list || [];
    outputBlocker.setAttribute("data-mode", mode);
    outputBlocker.innerHTML = "";
    list.forEach(item => {
        var li = document.createElement('li');
        li.textContent = item;
        outputBlocker.appendChild(li);
    });
}

// As-you-type instant (en|de)cryption.
var instantActionInProgress = false;
function instantAction() {
    if (instantActionInProgress) return;
    instantActionInProgress = true;

    var cryptionMode = getCryptionMode();

    if (!!textInput.value && !!passwordInput.value) {
        if (cryptionMode === 'encrypt') {
            aesBuddy.encrypt(passwordInput.value, textInput.value)
                .then(hex => {
                    textOutput.value = hex;
                    bottomLink.textContent = bottomLink.href = "#" + hex;
                    return hex;
                })
                .then(hex => { setOutputBlocker({mode: "off", list: []}); })
                .catch(error => {
                    textOutput.value = "";
                    bottomLink.textContent = bottomLink.href = "#";
                    setOutputBlocker({mode: "error", list: ["encryption error"]});
                })
                .then(()=>{ instantActionInProgress = false; });
        }
        else {
            aesBuddy.decrypt(passwordInput.value, textInput.value)
                .then(text => {
                    textOutput.value = text;
                    bottomLink.textContent = bottomLink.href = "#";
                    return text;
                })
                .then(text => { setOutputBlocker({mode: "off", list: []}) })
                .catch(error => {
                    textOutput.value = "";
                    bottomLink.textContent = bottomLink.href = "#";
                    setOutputBlocker({mode: "error", list: ["invalid"]});
                })
                .then(()=>{ instantActionInProgress = false; });
        }
    }
    else {
        textOutput.value = "";
        bottomLink.textContent = bottomLink.href = "#";
        setOutputBlocker({mode: "plain", list: ["enter some input text and a password above"]});
        instantActionInProgress = false;
    }
}

// Bindings for instant action.
textInput.addEventListener('keyup', instantAction);
passwordInput.addEventListener('keyup', instantAction);
encryptButton.addEventListener('change', instantAction);
decryptButton.addEventListener('change', instantAction);

// Flyout toggle.
var flyoutActive = false;
var plate = document.querySelector('.plate');
function toggleHandler(event) {
    flyoutActive = !flyoutActive;
    plate.setAttribute("data-flyout", flyoutActive ? "active" : "hidden");
    if (event) event.preventDefault();
    return false;
}
var toggleButtons = document.querySelectorAll('.flyout-toggle');
for (var i=0; i<toggleButtons.length; i++)
    toggleButtons[i].onclick = toggleHandler;

// Initializing with decryption data from URL.
function interpretHash() {
    var hash = /(?:^|#)([0-9a-fA-f]{10,})/i.exec(window.location.hash);
    if (hash) {
        var hex = hash[1];
        textInput.value = hex;
        setCryptionMode('decrypt');
        passwordInput.focus();
        instantAction();
    }
    window.location.hash = ''; // Removing hash afterwards.
}
window.addEventListener('hashchange', interpretHash);
interpretHash();

// Initial instant action.
instantAction();<commit_msg>Flyout toggle is now persistant with localStorage.<commit_after>////
//// PasteSafe web app.
////

// Forcing HTTPS in production.
var production = /github\.io/i.test(window.location.href) || /pastesafe\.com/i.test(window.location.href);
if (production && !/https/i.test(window.location.protocol))
    window.location.href = "https:" + window.location.href.substring(window.location.protocol.length);

// Obtaining references to PasteSafe DOM elements.
var root = document.querySelector('[paste-safe]');
var textInput = root.querySelector('textarea.text-input');
var textOutput = root.querySelector('textarea.text-output');
var passwordInput = root.querySelector('input.password');
var encryptButton = root.querySelector('.encrypt');
var decryptButton = root.querySelector('.decrypt');
var outputBlocker = root.querySelector('.output-blocker');
var bottomLink = root.querySelector('.bottom-link');
var getCryptionMode = () => root.querySelector('input[name="cryption_mode"]:checked').value;

// Handling the switch between 'encrypt' and 'decrypt' cryption mode.
function refreshCryptionMode() {
    var cryptionMode = getCryptionMode();
    if (cryptionMode === 'encrypt') {
        root.setAttribute('data-cryption-mode', 'encrypt');
        decryptButton.parentElement.removeAttribute('data-checked');
        encryptButton.parentElement.setAttribute('data-checked', '');
    }
    else {
        root.setAttribute('data-cryption-mode', 'decrypt');
        encryptButton.parentElement.removeAttribute('data-checked');
        decryptButton.parentElement.setAttribute('data-checked', '');
    }
}
encryptButton.addEventListener('change', refreshCryptionMode);
decryptButton.addEventListener('change', refreshCryptionMode);
refreshCryptionMode();

function setCryptionMode(mode) {
    encryptButton.checked = (mode==='encrypt') ?true :false;
    decryptButton.checked = (mode==='decrypt') ?true :false;
    refreshCryptionMode();
}

// Blocking the output textarea with a message.
// Modes:
//  - off: no output blocker.
//  - plain: subtle blocker with a simple message.
//  - error: angry blocker that indicates something went wrong.
function setOutputBlocker(options) {
    var mode = options.mode || "off";
    var list = options.list || [];
    outputBlocker.setAttribute("data-mode", mode);
    outputBlocker.innerHTML = "";
    list.forEach(item => {
        var li = document.createElement('li');
        li.textContent = item;
        outputBlocker.appendChild(li);
    });
}

// As-you-type instant (en|de)cryption.
var instantActionInProgress = false;
function instantAction() {
    if (instantActionInProgress) return;
    instantActionInProgress = true;

    var cryptionMode = getCryptionMode();

    if (!!textInput.value && !!passwordInput.value) {
        if (cryptionMode === 'encrypt') {
            aesBuddy.encrypt(passwordInput.value, textInput.value)
                .then(hex => {
                    textOutput.value = hex;
                    bottomLink.textContent = bottomLink.href = "#" + hex;
                    return hex;
                })
                .then(hex => { setOutputBlocker({mode: "off", list: []}); })
                .catch(error => {
                    textOutput.value = "";
                    bottomLink.textContent = bottomLink.href = "#";
                    setOutputBlocker({mode: "error", list: ["encryption error"]});
                })
                .then(()=>{ instantActionInProgress = false; });
        }
        else {
            aesBuddy.decrypt(passwordInput.value, textInput.value)
                .then(text => {
                    textOutput.value = text;
                    bottomLink.textContent = bottomLink.href = "#";
                    return text;
                })
                .then(text => { setOutputBlocker({mode: "off", list: []}) })
                .catch(error => {
                    textOutput.value = "";
                    bottomLink.textContent = bottomLink.href = "#";
                    setOutputBlocker({mode: "error", list: ["invalid"]});
                })
                .then(()=>{ instantActionInProgress = false; });
        }
    }
    else {
        textOutput.value = "";
        bottomLink.textContent = bottomLink.href = "#";
        setOutputBlocker({mode: "plain", list: ["enter some input text and a password above"]});
        instantActionInProgress = false;
    }
}

// Bindings for instant action.
textInput.addEventListener('keyup', instantAction);
passwordInput.addEventListener('keyup', instantAction);
encryptButton.addEventListener('change', instantAction);
decryptButton.addEventListener('change', instantAction);

// Flyout toggle.
var plate = document.querySelector('.plate');
plate.setAttribute("data-flyout", window.localStorage.getItem("flyout") || "active");
function toggleHandler(event) {
    var currentStatus = plate.getAttribute("data-flyout");
    var newStatus = currentStatus==="active" ?"hidden" :"active";
    plate.setAttribute("data-flyout", newStatus);
    window.localStorage.setItem("flyout", newStatus);
    if (event) event.preventDefault();
    return false;
}
var toggleButtons = document.querySelectorAll('.flyout-toggle');
for (var i=0; i<toggleButtons.length; i++)
    toggleButtons[i].onclick = toggleHandler;

// Initializing with decryption data from URL.
function interpretHash() {
    var hash = /(?:^|#)([0-9a-fA-f]{10,})/i.exec(window.location.hash);
    if (hash) {
        var hex = hash[1];
        textInput.value = hex;
        setCryptionMode('decrypt');
        passwordInput.focus();
        instantAction();
    }
    window.location.hash = ''; // Removing hash afterwards.
}
window.addEventListener('hashchange', interpretHash);
interpretHash();

// Initial instant action.
instantAction();<|endoftext|>


<commit_before>/**
  AuthGateway Middleware
  @description Exposes an API to create a user token schema and registers
    the required middleware for verifying and unpacking user data into the req
    object, also exposes an API for generating user tokens with a given payload
  @author tylerFowler
**/
'use strict';

module.exports = exports = AuthGW;

/**
  @constructor AuthGW
  @desc Factory function that creates a new gateway manager instance with
    the configured settings
  @param { String[] } roles - list of all possible user roles from lowest
    access level to highest access level
  @param { String } authorityName - serves as the JWT 'issuer' name
  @param { Object } dataSchema - defines the keys you expect to write to tokens
  @returns AuthGW instance
**/
let AuthGW = module.exports = exports =
function AuthGW(roles, authorityName, dataSchema) {
  if (!Array.isArray(roles)) roles = [roles];
};
<commit_msg>Added constructor, implemented a few basic fns<commit_after>/**
  AuthGateway Middleware
  @description Exposes an API to create a user token schema and registers
    the required middleware for verifying and unpacking user data into the req
    object, also exposes an API for generating user tokens with a given payload
  @author tylerFowler
**/
'use strict';

const crypto  = require('crypto');
const Promise = require('bluebird');
const JWT     = Promise.promisifyAll(require('jsonwebtoken'));

module.exports = exports = AuthGW;

// secondary components
let middleware = exports.Middleware = {};

/**
  @constructor AuthGW
  @desc Constructor function that creates a new gateway manager instance with
    the configured settings
  @param { String[] } roles - list of all possible user roles from lowest
    access level to highest access level :optional
  @param { String } authorityName - serves as the JWT 'issuer' name
  @param { Object } dataSchema - defines the keys you expect to write to tokens
  @param { Object } opts
  @returns AuthGW instance
**/
module.exports = exports = AuthGW;
function AuthGW(roles, authorityName, dataSchema, opts) {
  if (!Array.isArray(roles)) roles = [roles];

  this.roles = roles;
  this.authorityName = authorityName;
  this.dataSchema = dataSchema; // TODO: could we give functions to be evaluated?
  this.opts = Object.assign({
    tokenHeader: 'x-access-token',
    tokenSecret: crypto.randomBytes(24).toString('hex'),
    tokenExpiredCode: 419
  }, opts);
}

/**
  @name AuthGW#verifyAuthToken
  @desc Verifies that a given token is valid, unexpired, and trusted
  @param { String } token is the encrypted auth token
  @returns Promise<Object> contains the token's data
**/
AuthGW.prototype.verifyAuthToken = function verifyAuthtoken(token) {
  return JWT
  .verifyAsync(token, this.opts.tokenSecret, { issuer: this.authorityName });
};

/**
  @name AuthGW#middleware
  @desc Factory that creates the two Express middleware functions necessary
    for writing the data we need & verifying the auth token
  @returns [ verifyTokenFn(req,res,next), injectDataFn(req,res,next) ]
**/
AuthGW.prototype.middleware = function createMiddleware() {
  return [
    middleware.verifyTokenExpress.call(this),
    middleware.injectTokenDataExpress.call(this)
  ];
};

/**
  @name Middleware#verifyToken
  @desc ExpressJS flavor of the verify token middleware, verifies the auth token
    Note that if no auth token was given we *will* move along, but without
    writing any data to the request object
  @returns { Function } verifyToken
  @returns 401 if the given token is invalid or expired
**/
middleware.verifyTokenExpress = function verifyToken() {
  return (req, res, next) => {
    const authToken = req.headers[this.opts.tokenHeader];

    // if there's no token just don't inject the user data
    if (!authToken) return next();

    this.verifyAuthToken(authToken)
    .then(tokenData => {
      req._tokenData = tokenData;
      next();
    })

    // NOTE: it is **vitally** important that the client does *not* send a
    // another request with this token after receiving this error code
    // (say to prompt signin) or else this will be sent again,
    // resulting in an infinite loop
    .catch(
      JWT.TokenExpiredError, () => res.sendStatus(this.opts.tokenExpiredCode)
    )

    // token is malformed or otherwise unreadable
    .catch(JWT.JsonWebTokenError, () =>
      res.status(401).send('Invalid authorization token')
    )

    // general error, send 500
    .catch(() => res.sendStatus(500));
  };
};

/**
  @name Middleware#injectTokenData
  @desc ExpressJS flavor of the injection middleware, injects the decoded
    auth token's data into the req object, returning an error if a required
    field from the schema is missing
  @returns { Function } injectTokenData
  @returns 401 if the given token is missing required data
**/
middleware.injectTokenDataExpress = function injectTokenData() {
  return (req, res, next) => {
    const data = req._tokenData;
    // TODO:
    // - validate data fields match schema, throw away anything extra
    // - write schema fields into request object
  };
};
<|endoftext|>


<commit_before>/* global hexo */

var isEnabled = process.env.NODE_ENV !== 'development' &&
  (hexo.config.hasOwnProperty('all_minifier') === false || hexo.config.all_minifier === true);

if (isEnabled) {
  // HTML minifier
  hexo.config.html_minifier = Object.assign({
    enable: true,
    exclude: [],
    ignoreCustomComments: [/^\s*more/],
    removeComments: true,
    removeCommentsFromCDATA: true,
    collapseWhitespace: true,
    collapseBooleanAttributes: true,
    removeEmptyAttributes: true,
    minifyJS: true,
    minifyCSS: true
  }, hexo.config.html_minifier);

  // Css minifier
  hexo.config.css_minifier = Object.assign({
    enable: true,
    exclude: ['*.min.css']
  }, hexo.config.css_minifier);

  // Js minifier
  hexo.config.js_minifier = Object.assign({
    enable: true,
    mangle: true,
    output: {},
    compress: {},
    exclude: ['*.min.js']
  }, hexo.config.js_minifier);

  // Image minifier
  hexo.config.image_minifier = Object.assign({
    enable: true,
    interlaced: false,
    multipass: false,
    optimizationLevel: 3,
    pngquant: false,
    progressive: false
  }, hexo.config.image_minifier);

  // Js concator
  hexo.config.js_concator = Object.assign({
    enable: true,
    bundlePath: '/js/bundle.js',
  }, hexo.config.js_concator);

  hexo.extend.filter.register('after_render:html', require('./lib/optimizeHTML'));

  hexo.extend.filter.register('after_render:css', require('./lib/optimizeCSS'));

  hexo.extend.filter.register('after_render:js', require('./lib/optimizeJS'));

  hexo.extend.filter.register('after_generate', require('./lib/optimizeImage'));

  hexo.extend.filter.register('after_generate', require('./lib/concatJS'));
}
<commit_msg>fix: the default path<commit_after>/* global hexo */

var isEnabled = process.env.NODE_ENV !== 'development' &&
  (hexo.config.hasOwnProperty('all_minifier') === false || hexo.config.all_minifier === true);

if (isEnabled) {
  // HTML minifier
  hexo.config.html_minifier = Object.assign({
    enable: true,
    exclude: [],
    ignoreCustomComments: [/^\s*more/],
    removeComments: true,
    removeCommentsFromCDATA: true,
    collapseWhitespace: true,
    collapseBooleanAttributes: true,
    removeEmptyAttributes: true,
    minifyJS: true,
    minifyCSS: true
  }, hexo.config.html_minifier);

  // Css minifier
  hexo.config.css_minifier = Object.assign({
    enable: true,
    exclude: ['*.min.css']
  }, hexo.config.css_minifier);

  // Js minifier
  hexo.config.js_minifier = Object.assign({
    enable: true,
    mangle: true,
    output: {},
    compress: {},
    exclude: ['*.min.js']
  }, hexo.config.js_minifier);

  // Image minifier
  hexo.config.image_minifier = Object.assign({
    enable: true,
    interlaced: false,
    multipass: false,
    optimizationLevel: 3,
    pngquant: false,
    progressive: false
  }, hexo.config.image_minifier);

  // Js concator
  hexo.config.js_concator = Object.assign({
    enable: true,
    bundlePath: 'js/bundle.js',
  }, hexo.config.js_concator);

  hexo.extend.filter.register('after_render:html', require('./lib/optimizeHTML'));

  hexo.extend.filter.register('after_render:css', require('./lib/optimizeCSS'));

  hexo.extend.filter.register('after_render:js', require('./lib/optimizeJS'));

  hexo.extend.filter.register('after_generate', require('./lib/optimizeImage'));

  hexo.extend.filter.register('after_generate', require('./lib/concatJS'));
}
<|endoftext|>


<commit_before>// json-fix-stream by angleman, MIT
// Fix malformed JSON stream
"use strict"

var xtend     = require('xtend')    // Raynos/xtend
, util        = require('util')
, S           = require('string')   // jprichardson/string.js
, stream      = require('stream').Transform
if (!stream) stream = require('readable-stream').Transform // stream 2 compatible

// json string in and out
function JsonFixStream(config) {
 	stream.call(this, { objectMode: true })
	config = (config) ? config : {}
	var DEFAULT = {
		onErrors:        'ignore', // options: 'log' 'emit', 'throw', everything else is ignore
		cleanWhiteSpace: false,
		replace:         {}
	}
	config = xtend(DEFAULT, config)

	function tryToParse(json) {
		var parsed = undefined
		try {
			parsed = JSON.parse(json)
		} catch (e) {
			parsed = undefined
		}
		return parsed
	}

	this._transform = function (data, encoding, callback) {
		function handleError(json) {
			var msg = 'Could not fix: ' + json
			if (config.reference) msg = config.reference + ':' + msg
			switch (config.onErrors) {
				case 'log':   console.log(msg);        break
				case 'throw': throw new Error(msg);    break
				case 'emit':  self.emit('error', msg); break
			}
			callback()
		}

		if (data) {
			var json   = data.toString('utf8')
			var parsed = tryToParse(json)
			if (parsed === undefined) {
				var json2 = S(json).trim().s
				if (config.cleanWhiteSpace && json2.length == 0) {
					callback()
					return
				}
				var first       = json.substr(0,1)
				var last        = json.substr(-1)
				if (first == '[') {
					json2 += ']'
				} else if (first == '{') {
					json2 += '}'
				}
				parsed = tryToParse(json2)
/*				if (parsed === undefined) { // try removing trailing characters after last }
					json2 = S(json).trim().s.split('}')
					if (json2.length > 0) {
						delete json2[json2.length-1]
						json2 = json2.join('}')
						parsed = tryToParse(json2)
					}
				}
				if (parsed === undefined) { // try removing trailing characters after last ]
					json2 = S(json).trim().s.split(']')
					if (json2.length > 0) {
						delete json2[json2.length-1]
						json2 = json2.join(']')
						parsed = tryToParse(json2)
					}
				} */
			}
			if (parsed === undefined) return handleError(json)

			// todo: handle potential injections: http://media.blackhat.com/bh-us-11/Sullivan/BH_US_11_Sullivan_Server_Side_WP.pdf
			for (var i in parsed) {
				var val = parsed[i]
				if (typeof val == 'string' && config.cleanWhiteSpace) {
					val     = S(parsed[i]).collapseWhitespace().s
					val     = S(val).replaceAll("\0", '').s
					if (val != parsed[i]) {
						parsed[i] = val
					}
				}
				if (config.replace[i]) {
					delete parsed[i]
					parsed[config.replace[i]] = val
				}
			}
			data           = new Buffer(JSON.stringify(parsed), 'utf8')
			this.push(data)
		} else {
			this.push(data)
		}
		callback()
	};
}

util.inherits(JsonFixStream, stream)
module.exports = JsonFixStream
<commit_msg>expand fixes<commit_after>// json-fix-stream by angleman, MIT
// Fix malformed JSON stream
"use strict"

var xtend     = require('xtend')    // Raynos/xtend
, util        = require('util')
, S           = require('string')   // jprichardson/string.js
, stream      = require('stream').Transform
if (!stream) stream = require('readable-stream').Transform // stream 2 compatible

// json string in and out
function JsonFixStream(config) {
 	stream.call(this, { objectMode: true })
	config = (config) ? config : {}
	var DEFAULT = {
		onErrors:        'ignore', // options: 'log' 'emit', 'throw', everything else is ignore
		cleanWhiteSpace: false,
		replace:         {}
	}
	config = xtend(DEFAULT, config)

	function tryToParse(json) {
		var parsed = undefined
		try {
			parsed = JSON.parse(json)
		} catch (e) {
			parsed = undefined
		}
		return parsed
	}

	this._transform = function (data, encoding, callback) {
		function handleError(json) {
			var msg = 'Could not fix: ' + json
			if (config.reference) msg = config.reference + ':' + msg
			switch (config.onErrors) {
				case 'log':   console.log(msg);        break
				case 'throw': throw new Error(msg);    break
				case 'emit':  self.emit('error', msg); break
			}
			callback()
		}

		if (data) {
			var json   = data.toString('utf8')
			var parsed = tryToParse(json)
			if (parsed === undefined) {
				var json2 = S(json).trim().s
				if (config.cleanWhiteSpace && json2.length == 0) {
					callback()
					return
				}
				var first       = json.substr(0,1)
				var last        = json.substr(-1)
				if (first == '[') {
					json2 += ']'
				} else if (first == '{') {
					json2 += '}'
				}
				parsed = tryToParse(json2)
				if (parsed === undefined) { // try removing trailing characters after last }
					json2 = S(json).trim().s.split('}')
					if (json2.length > 0) {
						delete json2[json2.length-1]
						json2 = json2.join('}')
						parsed = tryToParse(json2)
					}
				}
				if (parsed === undefined) { // try removing trailing characters after last ]
					json2 = S(json).trim().s.split(']')
					if (json2.length > 0) {
						delete json2[json2.length-1]
						json2 = json2.join(']')
						parsed = tryToParse(json2)
					}
				}
			}
			if (parsed === undefined) return handleError(json)

			// todo: handle potential injections: http://media.blackhat.com/bh-us-11/Sullivan/BH_US_11_Sullivan_Server_Side_WP.pdf
			for (var i in parsed) {
				var val = parsed[i]
				if (typeof val == 'string' && config.cleanWhiteSpace) {
					val     = S(parsed[i]).collapseWhitespace().s
					val     = S(val).replaceAll("\0", '').s
					if (val != parsed[i]) {
						parsed[i] = val
					}
				}
				if (config.replace[i]) {
					delete parsed[i]
					parsed[config.replace[i]] = val
				}
			}
			data           = new Buffer(JSON.stringify(parsed), 'utf8')
			this.push(data)
		} else {
			this.push(data)
		}
		callback()
	};
}

util.inherits(JsonFixStream, stream)
module.exports = JsonFixStream
<|endoftext|>


<commit_before>var path = require('path')
var fs = require('fs')

function find (fileOrDir, toFind, dir) {
  var pieces = dir.split(path.sep)

  return new Promise(function (resolve, reject) {
    tryStat(pieces)

    function tryStat (dirPieces) {
      if (!dirPieces.length) {
        return resolve(null)
      }

      var check = dirPieces.concat(toFind).join(path.sep)

      fs.stat(check, interpretResult)

      function interpretResult (err, stats) {
        if (err || !stats[fileOrDir === 'dir' ? 'isDirectory' : 'isFile']()) {
          return tryStat(dirPieces.slice(0, -1))
        }

        resolve(check)
      }
    }
  })
}

find.dir = find.bind(null, 'dir')
find.file = find.bind(null, 'file')

module.exports = find
<commit_msg>use promise polyfill<commit_after>'use strict'

var path = require('path')
var fs = require('fs')

var Promise = require('es6-promise').Promise

function find (fileOrDir, toFind, dir) {
  var pieces = dir.split(path.sep)

  return new Promise(function (resolve, reject) {
    tryStat(pieces)

    function tryStat (dirPieces) {
      if (!dirPieces.length) {
        return resolve(null)
      }

      var check = dirPieces.concat(toFind).join(path.sep)

      fs.stat(check, interpretResult)

      function interpretResult (err, stats) {
        if (err || !stats[fileOrDir === 'dir' ? 'isDirectory' : 'isFile']()) {
          return tryStat(dirPieces.slice(0, -1))
        }

        resolve(check)
      }
    }
  })
}

find.dir = find.bind(null, 'dir')
find.file = find.bind(null, 'file')

module.exports = find
<|endoftext|>


<commit_before>// license: MIT
'use strict';

var gutil = require('gulp-util');
var through = require('through2');
var markdox = require('markdox');
var path = require('path');
var async = require('async');
var _ = require('underscore');

module.exports = function(options) {
  var stream = gutil.noop();

  var output = [];
  var afterRender = stream
    .pipe(module.exports.parse(options))
    .pipe(module.exports.format())
    .pipe(module.exports.render())
    .pipe(through.obj(function(chunk, enc, callback) {
      output.push(chunk);
      return callback();
    }));

  function write(chunk, enc, callback) {
    return stream.write(chunk, enc, callback);
  }

  function flush(callback) {
    var self = this;
    afterRender.on('finish', function(err) {
      output.forEach(self.push.bind(self));
      callback(err)
    });
    stream.end();
  }

  var retVal = through.obj(write, flush);
  return retVal;
};

_.extend(module.exports, {
  parse: stream(requireBuffer(parse), noop),
  format: stream(requireProperty('javadoc', format), noop),
  render: stream(requireProperty('formattedDoc', maybeConcat), render, createArray('chunks')),
});

function parse(self, options, chunk, callback) {
  chunk.path = path.relative(process.cwd(), chunk.path);
  chunk.cwd = process.cwd();

  markdox.parse(chunk.path, options, function(err, doc) {
    if (err) {
      self.emit('error', gulpError(err));
      return callback();
    }

    chunk.javadoc = doc;
    self.push(chunk);
    return callback();
  });
}

function format(self, options, chunk, callback) {
  try {
    chunk.formattedDoc = options.formatter({
      filename: chunk.path,
      javadoc: chunk.javadoc,
    });
    if (!chunk.formattedDoc) {
      self.emit('error', gulpError('No document returned from formatter: '+ chunk.formatterDoc));
    }
    self.push(chunk);
    return callback();

  } catch(e) {
    self.emit('error', gulpError(e));
    return callback(e);
  }
}

function maybeConcat(self, options, chunk, callback) {
  var path = chunk.path;
  if (typeof options.concat === 'string') {
    path = options.concat;
  }

  var chunks = self.chunks;
  (chunks[path] = chunks[path] || []).push(chunk);
  return callback();
}

function render(self, callback) {
  // intermediate map used to assure
  // the same order of chunks after async processing
  var rendered = {};
  var length = 0;

  async.each(_.keys(self.chunks), render0, flush);

  function render0(outputPath, cb) {
    var input = self.chunks[outputPath];
    var inputDocs = input.map(function(file) { return file.formattedDoc; });
    var options = input[0].markdoxOptions;

    var index = length++;

    markdox.generate(inputDocs, options, function(err, result) {
      if (err) {
        self.emit('error', gulpError(err));
        return cb(err);
      }
      var file = new gutil.File({ path: outputPath });
      file.contents = new Buffer(result);
      rendered[index] = file;
      return cb();
    });
  }

  function flush(err) {
    _.keys(rendered)
      .sort(function(a, b) { return a > b; })
      .map(function(index) { return rendered[index]; })
      .forEach(function(file) { self.push(file); })
    ;
    callback(err);
  }
}

function noop(self, callback) {
  return callback();
}

function stream(transform, flush) {
  var initializers = [].slice.call(arguments, 2);

  return function(options) {
    function transformDecorator(chunk, enc, callback) {
      chunk.markdoxOptions = _.defaults(options || chunk.markdoxOptions || {}, {
        output: false,
        encoding: enc,
        formatter: markdox.defaultFormatter,
      });
      if (chunk.isNull()) {
        this.push(chunk);
        return callback();
      }
      return transform(this, chunk.markdoxOptions, chunk, callback);
    }

    function flushDecorator(callback) {
      return flush(this, callback);
    }

    var retVal = through.obj(transformDecorator, flushDecorator);
    initializers.forEach(function(init) { init(retVal); });
    return retVal;
  };
}

function requireBuffer(chunkHandler) {
  return function(self, options, chunk, callback) {
    if (chunk.isStream()) {
      self.emit('error', gulpError('Streams are not supported'));
      return callback();
    }

    return chunkHandler(self, options, chunk, callback);
  };
}

function requireProperty(propertyName, chunkHandler) {
  return function(self, options, chunk, callback) {
    if (typeof chunk[propertyName] === 'undefined') {
      self.emit('error', gulpError('Couldn\'t find property on data chunk: "'+ propertyName +'"'));
      return callback();
    }

    return chunkHandler(self, options, chunk, callback);
  };
}

function createArray(propertyName) {
  return function(self) {
    self[propertyName] = [];
  };
}

function gulpError(message) {
  return new gutil.PluginError('gulp-markdox', message);
}

<commit_msg>+ passing options to formatter<commit_after>// license: MIT
'use strict';

var gutil = require('gulp-util');
var through = require('through2');
var markdox = require('markdox');
var path = require('path');
var async = require('async');
var _ = require('underscore');

module.exports = function(options) {
  var stream = gutil.noop();

  var output = [];
  var afterRender = stream
    .pipe(module.exports.parse(options))
    .pipe(module.exports.format())
    .pipe(module.exports.render())
    .pipe(through.obj(function(chunk, enc, callback) {
      output.push(chunk);
      return callback();
    }));

  function write(chunk, enc, callback) {
    return stream.write(chunk, enc, callback);
  }

  function flush(callback) {
    var self = this;
    afterRender.on('finish', function(err) {
      output.forEach(self.push.bind(self));
      callback(err)
    });
    stream.end();
  }

  var retVal = through.obj(write, flush);
  return retVal;
};

_.extend(module.exports, {
  parse: stream(requireBuffer(parse), noop),
  format: stream(requireProperty('javadoc', format), noop),
  render: stream(requireProperty('formattedDoc', maybeConcat), render, createArray('chunks')),
});

function parse(self, options, chunk, callback) {
  chunk.path = path.relative(process.cwd(), chunk.path);
  chunk.cwd = process.cwd();

  markdox.parse(chunk.path, options, function(err, doc) {
    if (err) {
      self.emit('error', gulpError(err));
      return callback();
    }

    chunk.javadoc = doc;
    self.push(chunk);
    return callback();
  });
}

function format(self, options, chunk, callback) {
  try {
    chunk.formattedDoc = options.formatter({
      filename: chunk.path,
      javadoc: chunk.javadoc,
      options: options,
    });
    if (!chunk.formattedDoc) {
      self.emit('error', gulpError('No document returned from formatter: '+ chunk.formatterDoc));
    }
    self.push(chunk);
    return callback();

  } catch(e) {
    self.emit('error', gulpError(e));
    return callback(e);
  }
}

function maybeConcat(self, options, chunk, callback) {
  var path = chunk.path;
  if (typeof options.concat === 'string') {
    path = options.concat;
  }

  var chunks = self.chunks;
  (chunks[path] = chunks[path] || []).push(chunk);
  return callback();
}

function render(self, callback) {
  // intermediate map used to assure
  // the same order of chunks after async processing
  var rendered = {};
  var length = 0;

  async.each(_.keys(self.chunks), render0, flush);

  function render0(outputPath, cb) {
    var input = self.chunks[outputPath];
    var inputDocs = input.map(function(file) { return file.formattedDoc; });
    var options = input[0].markdoxOptions;

    var index = length++;

    markdox.generate(inputDocs, options, function(err, result) {
      if (err) {
        self.emit('error', gulpError(err));
        return cb(err);
      }
      var file = new gutil.File({ path: outputPath });
      file.contents = new Buffer(result);
      rendered[index] = file;
      return cb();
    });
  }

  function flush(err) {
    _.keys(rendered)
      .sort(function(a, b) { return a > b; })
      .map(function(index) { return rendered[index]; })
      .forEach(function(file) { self.push(file); })
    ;
    callback(err);
  }
}

function noop(self, callback) {
  return callback();
}

function stream(transform, flush) {
  var initializers = [].slice.call(arguments, 2);

  return function(options) {
    function transformDecorator(chunk, enc, callback) {
      chunk.markdoxOptions = _.defaults(options || chunk.markdoxOptions || {}, {
        output: false,
        encoding: enc,
        formatter: markdox.defaultFormatter,
      });
      if (chunk.isNull()) {
        this.push(chunk);
        return callback();
      }
      return transform(this, chunk.markdoxOptions, chunk, callback);
    }

    function flushDecorator(callback) {
      return flush(this, callback);
    }

    var retVal = through.obj(transformDecorator, flushDecorator);
    initializers.forEach(function(init) { init(retVal); });
    return retVal;
  };
}

function requireBuffer(chunkHandler) {
  return function(self, options, chunk, callback) {
    if (chunk.isStream()) {
      self.emit('error', gulpError('Streams are not supported'));
      return callback();
    }

    return chunkHandler(self, options, chunk, callback);
  };
}

function requireProperty(propertyName, chunkHandler) {
  return function(self, options, chunk, callback) {
    if (typeof chunk[propertyName] === 'undefined') {
      self.emit('error', gulpError('Couldn\'t find property on data chunk: "'+ propertyName +'"'));
      return callback();
    }

    return chunkHandler(self, options, chunk, callback);
  };
}

function createArray(propertyName) {
  return function(self) {
    self[propertyName] = [];
  };
}

function gulpError(message) {
  return new gutil.PluginError('gulp-markdox', message);
}

<|endoftext|>


<commit_before>var Twitter = require('twitter');
var config = require('./config');

var client = new Twitter(config);

var username = process.env.USERNAME;
var params = { screen_name: username, stringify_ids: true };

var first_degree_list = [];
var second_degree_list = [];

function get_request(request, params, callback) {
	client.get(request, params, function(error, data, response) {
		if (error) {
			if (error[0].code === 88) {
				setTimeout(function() {
					get_request(request, params, callback);
				}, 60 * 1000);
			} else {
				process.stdout.write('\n');
				console.log(error);
			}
		} else {
			callback(data);
		}
	});
}

function collect_data(params) {
	get_request('friends/ids', params, function(first_degree) {
		first_degree_list = first_degree_list.concat(first_degree.ids);

		if (first_degree.next_cursor > 0) {
			setTimeout(function() {
				params.cursor = first_degree.next_cursor;
				collect_data(params);
			}, 60 * 1000);
		} else {
			var index = 0;

			function loop() {
				writeProgress();

				setTimeout(function() {
					get_second_degree({ user_id: first_degree_list[index], stringify_ids: true }, function() {
						if (index < first_degree_list.length - 1) {
							index++;
							loop();
						} else {
							index++;
							writeProgress();
							show_results(second_degree_list.length);
						}
					});
				}, 60 * 1000);
			}

			function writeProgress() {
				process.stdout.clearLine();
				process.stdout.cursorTo(0);
				process.stdout.write('Progress: ' + index + '/' + first_degree.ids.length);
			}

			function get_second_degree(params, callback) {
				get_request('friends/ids', params, function(second_degree) {
					for (var i = 0; i < second_degree.ids.length; i++) {
						var existing_entry = false;

						for (var j = 0; j < second_degree_list.length; j++) {
							if (second_degree.ids[i] === second_degree_list[j].id) {
								existing_entry = true;
								second_degree_list[j].len++;
								break;
							}
						}

						if (!existing_entry) {
							second_degree_list.push({ id: second_degree.ids[i], len: 1 });
						}
					}

					if (second_degree.next_cursor > 0) {
						setTimeout(function() {
							params.cursor = second_degree.next_cursor;
							get_second_degree(params, callback);
						}, 60 * 1000);
					} else {
						callback();
					}
				});
			}

			function show_results(num_results) {
				if (num_results > second_degree_list.length) {
					num_results = second_degree_list.length;
				}

				process.stdout.write('\n');
				console.log('Results:');

				second_degree_list.sort(function(a, b) {
					return b.len - a.len;
				});

				var i = 0;

				function get_username() {
					if (i < num_results) {
						setTimeout(function() {
							get_request('users/show', { user_id: second_degree_list[i].id }, function(user) {
								second_degree_list[i].username = user.screen_name;
								console.log('  @' + second_degree_list[i].username + ' (' + second_degree_list[i].len + ')');
								i++;
								get_username();
							});
						}, 1 * 1000);
					}
				}

				get_username();
			}

			loop();
		}
	});
}

collect_data(params);<commit_msg>change display order of functions<commit_after>var Twitter = require('twitter');
var config = require('./config');

var client = new Twitter(config);

var username = process.env.USERNAME;
var params = { screen_name: username, stringify_ids: true };

var first_degree_list = [];
var second_degree_list = [];

function collect_data(params) {
	get_request('friends/ids', params, function(first_degree) {
		first_degree_list = first_degree_list.concat(first_degree.ids);

		if (first_degree.next_cursor > 0) {
			setTimeout(function() {
				params.cursor = first_degree.next_cursor;
				collect_data(params);
			}, 60 * 1000);
		} else {
			var index = 0;

			function loop() {
				writeProgress();

				setTimeout(function() {
					get_second_degree({ user_id: first_degree_list[index], stringify_ids: true }, function() {
						if (index < first_degree_list.length - 1) {
							index++;
							loop();
						} else {
							index++;
							writeProgress();
							show_results(second_degree_list.length);
						}
					});
				}, 60 * 1000);
			}

			function writeProgress() {
				process.stdout.clearLine();
				process.stdout.cursorTo(0);
				process.stdout.write('Progress: ' + index + '/' + first_degree.ids.length);
			}

			function get_second_degree(params, callback) {
				get_request('friends/ids', params, function(second_degree) {
					for (var i = 0; i < second_degree.ids.length; i++) {
						var existing_entry = false;

						for (var j = 0; j < second_degree_list.length; j++) {
							if (second_degree.ids[i] === second_degree_list[j].id) {
								existing_entry = true;
								second_degree_list[j].len++;
								break;
							}
						}

						if (!existing_entry) {
							second_degree_list.push({ id: second_degree.ids[i], len: 1 });
						}
					}

					if (second_degree.next_cursor > 0) {
						setTimeout(function() {
							params.cursor = second_degree.next_cursor;
							get_second_degree(params, callback);
						}, 60 * 1000);
					} else {
						callback();
					}
				});
			}

			function show_results(num_results) {
				if (num_results > second_degree_list.length) {
					num_results = second_degree_list.length;
				}

				process.stdout.write('\n');
				console.log('Results:');

				second_degree_list.sort(function(a, b) {
					return b.len - a.len;
				});

				var i = 0;

				function get_username() {
					if (i < num_results) {
						setTimeout(function() {
							get_request('users/show', { user_id: second_degree_list[i].id }, function(user) {
								second_degree_list[i].username = user.screen_name;
								console.log('  @' + second_degree_list[i].username + ' (' + second_degree_list[i].len + ')');
								i++;
								get_username();
							});
						}, 1 * 1000);
					}
				}

				get_username();
			}

			loop();
		}
	});
}

function get_request(request, params, callback) {
	client.get(request, params, function(error, data, response) {
		if (error) {
			if (error[0].code === 88) {
				setTimeout(function() {
					get_request(request, params, callback);
				}, 60 * 1000);
			} else {
				process.stdout.write('\n');
				console.log(error);
			}
		} else {
			callback(data);
		}
	});
}

collect_data(params);
<|endoftext|>


<commit_before>const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
const passport = require('passport');
const BearerStrategy = require('passport-http-bearer').Strategy;
const GoogleStrategy = require('passport-google-oauth20').Strategy;

const Messages = require('./models/messages');
const User = require('./models/user');

const HOST = process.env.HOST;

dotenv.config();
const frontendUrl = process.env.FRONTEND_URL;

mongoose.Promise = global.Promise;

// Prepend timestamp to all `logs`
const log = (...args) => console.log(new Date().toISOString(), ...args);

log(`Server running in ${process.env.NODE_ENV} mode`);

const app = express();
app.use(bodyParser.json());

app.all('/*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers',
    'Content-Type, '
    + 'Access-Control-Allow-Headers, '
    + 'Authorization, '
    + 'X-Requested-With'
  );
  next();
});

// ===== AUTH =====

passport.use(new BearerStrategy(
    (accessToken, done) => {
      // log(`token: ${accessToken}`);
      User.findOne({ accessToken })
      .then((user) => {
        log(`userId: ${user._id}`);
        done(null, user, { scope: 'read' });
      });
    }
));

passport.use(new GoogleStrategy({
  clientID: process.env.CLIENTID,
  clientSecret: process.env.CLIENTSECRET,
  callbackURL: `${process.env.BACKEND_URL}/auth/google/callback`
}, (accessToken, refreshToken, profile, done) => {
  log('=======', accessToken);

  User.findOneAndUpdate({ googleId: profile.id },
    {
      $set: {
        googleId: profile.id,
        nickname: profile.name.givenName || '',
        userName: profile.displayName || '',
        email: profile.emails[0].value || '',
        avatar: profile.photos[0].value || '',
        accessToken
      }
    },
    { upsert: true, new: true, setDefaultsOnInsert: true })
    .then((user) => {
      log('user', user);
      done(null, user);
    })
    .catch((err) => {
      log(err);
    });
}));

app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile', 'email'] })
);

app.get('/auth/google/callback',
  passport.authenticate('google',
    { failureRedirect: frontendUrl, session: false }
  ),

  ({ user }, res) => {
    log(`Authenticated user: ${user}`);
    res.cookie('accessToken', user.accessToken, { expires: 0, httpOnly: false });
    res.redirect(`${frontendUrl}/#/app`);
  }
);

app.get('/auth/logout', (req, res) => {
  req.logout();
  res.redirect(frontendUrl);
});

// ===== MESSAGES =====

app.get('/messages',
  passport.authenticate('bearer', { session: false }),

  ({ user }, res) => {
    log('GET /messages/');

    Messages.find().sort({ date: -1 })
    .then(messages =>
      res.json({
        currentUser: user._id,
        currentAvatar: user.avatar,
        currentNickname: user.nickname,
        messages: messages.map(message =>
          Object.assign(message, {
            comments: message.comments
              .filter(comment =>
                user._id.equals(comment.from) || user._id.equals(comment.to)
              )
              .sort((x, y) => new Date(x.date) - new Date(y.date))
          })
        ),
      })
    );
  }
);

app.post('/messages',
  passport.authenticate('bearer', { session: false }),

  ({ user, body }, res) => {
    log(`POST /messages, body: ${body}`);

    Messages.create(Object.assign(body, { userId: user._id }))
    .then(({ _id }) => {
      res.status(201).json({ _id });
    })
    .catch((err) => {
      log(`Err: ${err}`);
      res.sendStatus(404);
    });
  }
);

app.delete('/messages/:messageId',
  passport.authenticate('bearer', { session: false }),

  ({ user, params: { messageId } }, res) => {
    log(`DELETE /messages/${messageId}`);

    Messages.findOne({ _id: messageId, userId: user._id })
      .then((result) => {
        if (result) {
          result.remove();
          res.sendStatus(200);
        } else {
          res.sendStatus(404);
        }
      })
      .catch((err) => {
        console.error(err);
        res.sendStatus(404);
      });
  }
);

// ===== MEMBERS =====

app.get('/members', passport.authenticate('bearer', { session: false }),
  (req, res) => {
    log('GET /members');

    // When multiple families implemented, limit find to current family
    User.find({}, { accessToken: 0, __v: 0, googleId: 0 })

    .then(users => res.json(users))

    .catch((err) => {
      console.error(err);
      res.sendStatus(400);
    });
  }
);

// ===== CURRENT USER =====
// limited functionality now; to be used for multiple families functionality

app.get('/user', passport.authenticate('bearer', { session: false }),
  ({ user }, res) =>
    res.json({
      currentUser: {
        id: user._id,
        avatar: user.avatar,
        nickname: user.nickname,
        fullname: user.userName,
      }
    })
);

// ===== COMMENTS =====

app.post('/comments', passport.authenticate('bearer', { session: false }),
  ({ body, user }, res) => {
    log(`POST /comments/:${body.messageId}`);

    Messages.update(
      { _id: body.messageId },
      { $push: { comments: {
        from: user._id,
        to: body.to,
        text: body.text,
      } } }
    )

    .then((data) => {
      if (data.nModified > 0) {
        res.sendStatus(200);
      } else {
        res.sendStatus(404);
      }
    })

    .catch((err) => {
      console.error(err);
      res.sendStatus(404);
    });
  }
);

app.delete('/comments/:messageId/:commentId',
  passport.authenticate('bearer', { session: false }),
  ({ user, params: { messageId, commentId } }, res) => {
    log(`DELETE /comments/:${messageId}/:${commentId}`);

    Messages.update(
      { _id: messageId },
      { $pull: { comments: { _id: commentId, from: user._id } } }
    )
    .then((status) => {
      if (status.nModified > 0) {
        res.sendStatus(202);
      } else {
        res.sendStatus(404);
      }
    })
    .catch((err) => {
      console.error(err.message);
      return res.sendStatus(404);
    });
  }
);

// ===== SERVER =====

let server;

function runServer(callback) {
  return new Promise((resolve, reject) => {
    mongoose.connect(process.env.DATABASE_URL, (err) => {
      if (err && callback) {
        log(err);
        return callback(err);
      }
      return null;
    });
    server = app.listen(process.env.PORT, HOST, () => {
      log(`Your app is listening on port ${process.env.PORT}`);
      if (callback) {
        callback();
      }
      resolve(server);
    }).on('error', (err) => {
      reject(err);
    });
  });
}

function closeServer() {
  return new Promise((resolve, reject) => {
    log('Closing server');
    server.close((err) => {
      if (err) {
        reject(err);
        return;
      }
      resolve();
    });
  });
}

if (require.main === module) {
  runServer();
}

module.exports = { app, runServer, closeServer };
<commit_msg>specify url<commit_after>const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
const passport = require('passport');
const BearerStrategy = require('passport-http-bearer').Strategy;
const GoogleStrategy = require('passport-google-oauth20').Strategy;

const Messages = require('./models/messages');
const User = require('./models/user');

const HOST = process.env.HOST;

dotenv.config();
const frontendUrl = process.env.FRONTEND_URL;

mongoose.Promise = global.Promise;

// Prepend timestamp to all `logs`
const log = (...args) => console.log(new Date().toISOString(), ...args);

log(`Server running in ${process.env.NODE_ENV} mode`);

const app = express();
app.use(bodyParser.json());

app.all('/*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', frontendUrl);
  res.header('Access-Control-Allow-Headers',
    'Content-Type, '
    + 'Access-Control-Allow-Headers, '
    + 'Authorization, '
    + 'X-Requested-With'
  );
  next();
});

// ===== AUTH =====

passport.use(new BearerStrategy(
    (accessToken, done) => {
      // log(`token: ${accessToken}`);
      User.findOne({ accessToken })
      .then((user) => {
        log(`userId: ${user._id}`);
        done(null, user, { scope: 'read' });
      });
    }
));

passport.use(new GoogleStrategy({
  clientID: process.env.CLIENTID,
  clientSecret: process.env.CLIENTSECRET,
  callbackURL: `${process.env.BACKEND_URL}/auth/google/callback`
}, (accessToken, refreshToken, profile, done) => {
  log('=======', accessToken);

  User.findOneAndUpdate({ googleId: profile.id },
    {
      $set: {
        googleId: profile.id,
        nickname: profile.name.givenName || '',
        userName: profile.displayName || '',
        email: profile.emails[0].value || '',
        avatar: profile.photos[0].value || '',
        accessToken
      }
    },
    { upsert: true, new: true, setDefaultsOnInsert: true })
    .then((user) => {
      log('user', user);
      done(null, user);
    })
    .catch((err) => {
      log(err);
    });
}));

app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile', 'email'] })
);

app.get('/auth/google/callback',
  passport.authenticate('google',
    { failureRedirect: frontendUrl, session: false }
  ),

  ({ user }, res) => {
    log(`Authenticated user: ${user}`);
    res.cookie('accessToken', user.accessToken, { expires: 0, httpOnly: false });
    res.redirect(`${frontendUrl}/#/app`);
  }
);

app.get('/auth/logout', (req, res) => {
  req.logout();
  res.redirect(frontendUrl);
});

// ===== MESSAGES =====

app.get('/messages',
  passport.authenticate('bearer', { session: false }),

  ({ user }, res) => {
    log('GET /messages/');

    Messages.find().sort({ date: -1 })
    .then(messages =>
      res.json({
        currentUser: user._id,
        currentAvatar: user.avatar,
        currentNickname: user.nickname,
        messages: messages.map(message =>
          Object.assign(message, {
            comments: message.comments
              .filter(comment =>
                user._id.equals(comment.from) || user._id.equals(comment.to)
              )
              .sort((x, y) => new Date(x.date) - new Date(y.date))
          })
        ),
      })
    );
  }
);

app.post('/messages',
  passport.authenticate('bearer', { session: false }),

  ({ user, body }, res) => {
    log(`POST /messages, body: ${body}`);

    Messages.create(Object.assign(body, { userId: user._id }))
    .then(({ _id }) => {
      res.status(201).json({ _id });
    })
    .catch((err) => {
      log(`Err: ${err}`);
      res.sendStatus(404);
    });
  }
);

app.delete('/messages/:messageId',
  passport.authenticate('bearer', { session: false }),

  ({ user, params: { messageId } }, res) => {
    log(`DELETE /messages/${messageId}`);

    Messages.findOne({ _id: messageId, userId: user._id })
      .then((result) => {
        if (result) {
          result.remove();
          res.sendStatus(200);
        } else {
          res.sendStatus(404);
        }
      })
      .catch((err) => {
        console.error(err);
        res.sendStatus(404);
      });
  }
);

// ===== MEMBERS =====

app.get('/members', passport.authenticate('bearer', { session: false }),
  (req, res) => {
    log('GET /members');

    // When multiple families implemented, limit find to current family
    User.find({}, { accessToken: 0, __v: 0, googleId: 0 })

    .then(users => res.json(users))

    .catch((err) => {
      console.error(err);
      res.sendStatus(400);
    });
  }
);

// ===== CURRENT USER =====
// limited functionality now; to be used for multiple families functionality

app.get('/user', passport.authenticate('bearer', { session: false }),
  ({ user }, res) =>
    res.json({
      currentUser: {
        id: user._id,
        avatar: user.avatar,
        nickname: user.nickname,
        fullname: user.userName,
      }
    })
);

// ===== COMMENTS =====

app.post('/comments', passport.authenticate('bearer', { session: false }),
  ({ body, user }, res) => {
    log(`POST /comments/:${body.messageId}`);

    Messages.update(
      { _id: body.messageId },
      { $push: { comments: {
        from: user._id,
        to: body.to,
        text: body.text,
      } } }
    )

    .then((data) => {
      if (data.nModified > 0) {
        res.sendStatus(200);
      } else {
        res.sendStatus(404);
      }
    })

    .catch((err) => {
      console.error(err);
      res.sendStatus(404);
    });
  }
);

app.delete('/comments/:messageId/:commentId',
  passport.authenticate('bearer', { session: false }),
  ({ user, params: { messageId, commentId } }, res) => {
    log(`DELETE /comments/:${messageId}/:${commentId}`);

    Messages.update(
      { _id: messageId },
      { $pull: { comments: { _id: commentId, from: user._id } } }
    )
    .then((status) => {
      if (status.nModified > 0) {
        res.sendStatus(202);
      } else {
        res.sendStatus(404);
      }
    })
    .catch((err) => {
      console.error(err.message);
      return res.sendStatus(404);
    });
  }
);

// ===== SERVER =====

let server;

function runServer(callback) {
  return new Promise((resolve, reject) => {
    mongoose.connect(process.env.DATABASE_URL, (err) => {
      if (err && callback) {
        log(err);
        return callback(err);
      }
      return null;
    });
    server = app.listen(process.env.PORT, HOST, () => {
      log(`Your app is listening on port ${process.env.PORT}`);
      if (callback) {
        callback();
      }
      resolve(server);
    }).on('error', (err) => {
      reject(err);
    });
  });
}

function closeServer() {
  return new Promise((resolve, reject) => {
    log('Closing server');
    server.close((err) => {
      if (err) {
        reject(err);
        return;
      }
      resolve();
    });
  });
}

if (require.main === module) {
  runServer();
}

module.exports = { app, runServer, closeServer };
<|endoftext|>


<commit_before>'use strict';
var cheerio = require('cheerio');
var _ = require('underscore');
var multiline = require('multiline');

var template = _.template(multiline(function() {
  /*
     <a href="<%= url %>" title="<%= title %>" target="_self" class="fancybox">
       <img src="<%= url %>" alt="<%= title %>">

   */
}));

module.exports = {
  book: {
    assets: './assets',
    js: [
      'jquery.min.js',
      'jquery.mousewheel.pack.js',
      'jquery.fancybox.pack.js',
      'jquery.fancybox-buttons.js',
      'plugin.js'
    ],
    css: [
      'jquery.fancybox.css',
      'jquery.fancybox-buttons.css'
    ]
  },
  hooks: {
    page: function(page) {
      var $ = cheerio.load(page.content);

      $('img').each(function(index, img) {
        var $img = $(img);
        $img.replaceWith(template({
          url: $img.attr('src'),
          title: $img.attr('alt')
        }));
      });

      page.content = $.html();

      return page;
    }
  }
};
<commit_msg>added rel property to group images on the page into a gallery<commit_after>'use strict';
var cheerio = require('cheerio');
var _ = require('underscore');
var multiline = require('multiline');

var template = _.template(multiline(function() {
  /*
     <a href="<%= url %>" rel="grouped" title="<%= title %>" target="_self" class="fancybox">
       <img src="<%= url %>" alt="<%= title %>">

   */
}));

module.exports = {
  book: {
    assets: './assets',
    js: [
      'jquery.min.js',
      'jquery.mousewheel.pack.js',
      'jquery.fancybox.pack.js',
      'jquery.fancybox-buttons.js',
      'plugin.js'
    ],
    css: [
      'jquery.fancybox.css',
      'jquery.fancybox-buttons.css'
    ]
  },
  hooks: {
    page: function(page) {
      var $ = cheerio.load(page.content);

      $('img').each(function(index, img) {
        var $img = $(img);
        $img.replaceWith(template({
          url: $img.attr('src'),
          title: $img.attr('alt')
        }));
      });

      page.content = $.html();

      return page;
    }
  }
};
<|endoftext|>