<commit_before>var pull = require('pull-stream')

function destroy(stream, cb) {
  function onClose () {
    cleanup(); cb()
  }
  function onError (err) {
    cleanup(); cb(err)
  }
  function cleanup() {
    stream.removeListener('close', onClose)
    stream.removeListener('error', onError)
  }
  stream.on('close', onClose)
  stream.on('error', onError)
}

function write(read, stream) {
  var ended
  function onClose () {
    cleanup()
    if(!ended) read(ended = true, function () {})
  }
  function onError (err) {
    cleanup()
    if(!ended) read(ended = err, function () {})
  }
  function cleanup() {
    stream.removeListener('close', onClose)
    stream.removeListener('error', onError)
  }
  stream.on('close', onClose)
  stream.on('error', onError)
  process.nextTick(function next() {
    read(null, function (end, data) {
      if(end === true)
        return stream._isStdio || stream.end()
      if(ended = ended || end)
        return stream.emit('error', end)

      var pause = stream.write(data)
      if(pause === false)
        stream.once('drain', next)
      else next()
    })
  })
}

function first (emitter, events, handler) {
  function listener (val) {
    events.forEach(function (e) {
      emitter.removeListener(e, listener)
    })
    handler(val)
  }
  events.forEach(function (e) {
    emitter.on(e, listener)
  })
  return emitter
}

function read2(stream) {
  var ended = false, waiting = false
  var _cb

  function read () {
    var data = stream.read()
    if(data !== null && _cb) {
      var cb = _cb; _cb = null
      cb(null, data)
    }
  }

  stream.on('readable', function () {
    waiting = true
    _cb && read()
  })
  .on('end', function () {
    ended = true
    _cb && _cb(ended)
  })
  .on('error', function (err) {
    ended = err
    _cb && _cb(ended)
  })

  return function (end, cb) {
    _cb = cb
    if(waiting)
      read()
    return
    ;(function next () {
      console.log('READ')
      if(ended && ended !== true) //ERROR
        return cb(ended)
      var data = stream.read()
      console.log('data', data, ended)
      if(data == null) {
        if(ended)
          return cb(ended)
        _cb = cb
        stream.on('readable', next)
      } else {
        return cb(null, data)
      }
    })()
  }
}

function read(stream) {
  if('function' === typeof stream.read)
    return read2(stream)

  var buffer = [], cbs = [], ended, paused = false

  var draining
  function drain() {
    while((buffer.length || ended) && cbs.length)
      cbs.shift()(buffer.length ? null : ended, buffer.shift())
    if(!buffer.length && (paused)) {
      paused = false
      stream.resume()
    }
  }

  stream.on('data', function (data) {
    buffer.push(data)
    drain()
    if(buffer.length && stream.pause) {
      paused = true
      stream.pause()
    }
  })
  stream.on('end', function () {
    ended = true
    drain()
  })
  stream.on('error', function (err) {
    ended = err
    drain()
  })
  return function (abort, cb) {
    if(!cb) throw new Error('*must* provide cb')
    if(abort) {
      stream.once('close', function () {
        cb(abort)
      })
      stream.destroy()
    }
    cbs.push(cb)
    drain()
  }
}

module.exports = function (stream) {
  return (
    stream.writable
    ? stream.readable
      ? pull.Through(function (r) { write(r, stream); return read(stream) })()
      : pull.Sink(function (r) { return write(r, stream) })()
    : pull.Source(function () { return read(stream) })()
  )
}

<commit_msg>export sink and source<commit_after>var pull = require('pull-stream')

function destroy(stream, cb) {
  function onClose () {
    cleanup(); cb()
  }
  function onError (err) {
    cleanup(); cb(err)
  }
  function cleanup() {
    stream.removeListener('close', onClose)
    stream.removeListener('error', onError)
  }
  stream.on('close', onClose)
  stream.on('error', onError)
}

function write(read, stream) {
  var ended
  function onClose () {
    cleanup()
    if(!ended) read(ended = true, function () {})
  }
  function onError (err) {
    cleanup()
    if(!ended) read(ended = err, function () {})
  }
  function cleanup() {
    stream.removeListener('close', onClose)
    stream.removeListener('error', onError)
  }
  stream.on('close', onClose)
  stream.on('error', onError)
  process.nextTick(function next() {
    read(null, function (end, data) {
      if(end === true)
        return stream._isStdio || stream.end()
      if(ended = ended || end)
        return stream.emit('error', end)

      var pause = stream.write(data)
      if(pause === false)
        stream.once('drain', next)
      else next()
    })
  })
}

function first (emitter, events, handler) {
  function listener (val) {
    events.forEach(function (e) {
      emitter.removeListener(e, listener)
    })
    handler(val)
  }
  events.forEach(function (e) {
    emitter.on(e, listener)
  })
  return emitter
}

function read2(stream) {
  var ended = false, waiting = false
  var _cb

  function read () {
    var data = stream.read()
    if(data !== null && _cb) {
      var cb = _cb; _cb = null
      cb(null, data)
    }
  }

  stream.on('readable', function () {
    waiting = true
    _cb && read()
  })
  .on('end', function () {
    ended = true
    _cb && _cb(ended)
  })
  .on('error', function (err) {
    ended = err
    _cb && _cb(ended)
  })

  return function (end, cb) {
    _cb = cb
    if(waiting)
      read()
    return
    ;(function next () {
      console.log('READ')
      if(ended && ended !== true) //ERROR
        return cb(ended)
      var data = stream.read()
      console.log('data', data, ended)
      if(data == null) {
        if(ended)
          return cb(ended)
        _cb = cb
        stream.on('readable', next)
      } else {
        return cb(null, data)
      }
    })()
  }
}

function read(stream) {
  if('function' === typeof stream.read)
    return read2(stream)

  var buffer = [], cbs = [], ended, paused = false

  var draining
  function drain() {
    while((buffer.length || ended) && cbs.length)
      cbs.shift()(buffer.length ? null : ended, buffer.shift())
    if(!buffer.length && (paused)) {
      paused = false
      stream.resume()
    }
  }

  stream.on('data', function (data) {
    buffer.push(data)
    drain()
    if(buffer.length && stream.pause) {
      paused = true
      stream.pause()
    }
  })
  stream.on('end', function () {
    ended = true
    drain()
  })
  stream.on('error', function (err) {
    ended = err
    drain()
  })
  return function (abort, cb) {
    if(!cb) throw new Error('*must* provide cb')
    if(abort) {
      stream.once('close', function () {
        cb(abort)
      })
      stream.destroy()
    }
    cbs.push(cb)
    drain()
  }
}

var sink = function (stream) {
  return pull.Sink(function (read) {
    return write(read, stream)
  })()
}

var source = function (stream) {
  return pull.Source(function () { return read(stream) })()
}

exports = module.exports = function (stream) {
  return (
    stream.writable
    ? stream.readable
      ? pull.Through(function(_read) {
          write(_read, stream);
          return read(stream)
        })()
      : sink(stream)
    : source(stream)
  )
}

exports.sink = sink
exports.source = source
<|endoftext|>


<commit_before>/*!
 * option-cache <https://github.com/jonschlinkert/option-cache>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var Emitter = require('component-emitter');
var typeOf = require('kind-of');

/**
 * Lazily required modules
 */

var lazy = require('lazy-cache')(require);
var mapVisit = lazy('map-visit');
var get = lazy('get-value');
var set = lazy('set-value');
var has = lazy('has-value');
var toFlags = lazy('to-flags');

/**
 * Create a new instance of `Options`.
 *
 * ```js
 * var app = new Options();
 * ```
 *
 * @param {Object} `options` Initialize with default options.
 * @api public
 */

var Options = module.exports = function Options(options) {
  Emitter.call(this);
  this.options = options || {};
};

/**
 * Static method for mixing `Options` methods onto the
 * provided `object`.
 *
 * @param {Object} `object`
 * @return {Object}
 */

Options.mixin =function(object) {
  for (var key in Options.prototype) {
    object.prototype[key] = Options.prototype[key];
  }
  object.mixin = Options.mixin;
};

/**
 * `Options` prototype methods.
 */

Options.prototype = Emitter({
  constructor: Options,

  /**
   * Set or get an option.
   *
   * ```js
   * app.option('a', true);
   * app.option('a');
   * //=> true
   * ```
   *
   * @param {String} `key` The option name.
   * @param {*} `value` The value to set.
   * @return {*} Returns a `value` when only `key` is defined.
   * @api public
   */

  option: function(key, val) {
    if (typeOf(key) === 'string' && typeOf(val) === 'undefined') {
      if (key.indexOf('.') === -1) {
        return this.options[key];
      }
      return get()(this.options, key);
    }

    if (typeOf(key) === 'object' || typeOf(key) === 'array') {
      return this.mapVisit('option', [].slice.call(arguments));
    }

    set()(this.options, key, val);
    this.emit('option', key, val);
    return this;
  },

  /**
   * Enable `key`.
   *
   * ```js
   * app.enable('a');
   * ```
   * @param {String} `key`
   * @return {Object} `Options`to enable chaining
   * @api public
   */

  enable: function(key) {
    this.option(key, true);
    return this;
  },

  /**
   * Disable `key`.
   *
   * ```js
   * app.disable('a');
   * ```
   *
   * @param {String} `key` The option to disable.
   * @return {Object} `Options`to enable chaining
   * @api public
   */

  disable: function(key) {
    this.option(key, false);
    return this;
  },

  /**
   * Check if `prop` is enabled (truthy).
   *
   * ```js
   * app.enabled('a');
   * //=> false
   *
   * app.enable('a');
   * app.enabled('a');
   * //=> true
   * ```
   *
   * @param {String} `prop`
   * @return {Boolean}
   * @api public
   */

  enabled: function(prop) {
    return Boolean(this.option(prop));
  },

  /**
   * Check if `prop` is disabled (falsey).
   *
   * ```js
   * app.disabled('a');
   * //=> true
   *
   * app.enable('a');
   * app.disabled('a');
   * //=> false
   * ```
   *
   * @param {String} `prop`
   * @return {Boolean} Returns true if `prop` is disabled.
   * @api public
   */

  disabled: function(prop) {
    return !Boolean(this.option(prop));
  },

  /**
   * Returns true if the value of `prop` is strictly `true`.
   *
   * ```js
   * app.option('a', 'b');
   * app.isTrue('a');
   * //=> false
   *
   * app.option('c', true);
   * app.isTrue('c');
   * //=> true
   *
   * app.option({a: {b: {c: true}}});
   * app.isTrue('a.b.c');
   * //=> true
   * ```
   *
   * @param {String} `prop`
   * @return {Boolean} Uses strict equality for comparison.
   * @api public
   */

  isTrue: function(prop) {
    return this.option(prop) === true;
  },

  /**
   * Returns true if the value of `key` is strictly `false`.
   *
   * ```js
   * app.option('a', null);
   * app.isFalse('a');
   * //=> false
   *
   * app.option('c', false);
   * app.isFalse('c');
   * //=> true
   *
   * app.option({a: {b: {c: false}}});
   * app.isFalse('a.b.c');
   * //=> true
   * ```
   *
   * @param {String} `prop`
   * @return {Boolean} Uses strict equality for comparison.
   * @api public
   */

  isFalse: function(prop) {
    return this.option(prop) === false;
  },

  /**
   * Return true if the value of key is either `true`
   * or `false`.
   *
   * ```js
   * app.option('a', 'b');
   * app.isBoolean('a');
   * //=> false
   *
   * app.option('c', true);
   * app.isBoolean('c');
   * //=> true
   * ```
   *
   * @param {String} `key`
   * @return {Boolean} True if `true` or `false`.
   * @api public
   */

  isBoolean: function(prop) {
    return typeof this.option(prop) === 'boolean';
  },

  /**
   * Return true if `options.hasOwnProperty(key)`
   *
   * ```js
   * app.hasOption('a');
   * //=> false
   * app.option('a', 'b');
   * app.hasOption('a');
   * //=> true
   * ```
   *
   * @param {String} `prop`
   * @return {Boolean} True if `prop` exists.
   * @api public
   */

  hasOption: function(prop) {
    if (prop.indexOf('.') === -1) {
      return this.options.hasOwnProperty(prop);
    }
    return has(this.options, prop);
  },

  /**
   * Generate an array of command line args from
   * the given `keys` or all options.
   *
   * ```js
   * // set some options
   * app.option('foo', 'bar');
   * app.option('abc', true);
   * app.option('xyz', 10);
   * app.option('one', false);
   *
   * // create command line args for all options
   * app.flags();
   * //=> ['--foo=bar', '--abc', '--xyz=10', '--no-one']
   *
   * // or specific options
   * app.flags(['foo', 'abc']);
   * //=> ['--foo=bar', '--abc']
   * ```
   *
   * @param  {Array} `keys`
   * @return {Array} Array of args
   * @api public
   */

  flags: function(keys) {
    keys = keys || Object.keys(this.options);
    return toFlags()(this.options, keys);
  },

  /**
   * Map visit `method` over each object in the given array.
   *
   * @param  {String} `method`
   * @param  {Array} `arr`
   */

  mapVisit: function(method, arr) {
    mapVisit()(this, method, arr);
    return this;
  }
});
<commit_msg>update lazy-cache<commit_after>/*!
 * option-cache <https://github.com/jonschlinkert/option-cache>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var Emitter = require('component-emitter');
var typeOf = require('kind-of');

/**
 * Lazily required modules
 */

var lazy = require('lazy-cache')(require);
lazy('collection-visit', 'visit');
lazy('get-value', 'get');
lazy('set-value', 'set');
lazy('has-value', 'has');
lazy('to-flags', 'toFlags');

/**
 * Create a new instance of `Options`.
 *
 * ```js
 * var app = new Options();
 * ```
 *
 * @param {Object} `options` Initialize with default options.
 * @api public
 */

var Options = module.exports = function Options(options) {
  Emitter.call(this);
  this.options = options || {};
};

/**
 * Static method for mixing `Options` methods onto the
 * provided `object`.
 *
 * @param {Object} `object`
 * @return {Object}
 */

Options.mixin =function(object) {
  for (var key in Options.prototype) {
    object.prototype[key] = Options.prototype[key];
  }
  object.mixin = Options.mixin;
};

/**
 * `Options` prototype methods.
 */

Options.prototype = Emitter({
  constructor: Options,

  /**
   * Set or get an option.
   *
   * ```js
   * app.option('a', true);
   * app.option('a');
   * //=> true
   * ```
   *
   * @param {String} `key` The option name.
   * @param {*} `value` The value to set.
   * @return {*} Returns a `value` when only `key` is defined.
   * @api public
   */

  option: function(key, val) {
    if (typeOf(key) === 'string' && typeOf(val) === 'undefined') {
      if (key.indexOf('.') === -1) {
        return this.options[key];
      }
      return lazy.get(this.options, key);
    }

    if (typeOf(key) === 'object' || typeOf(key) === 'array') {
      return this.visit('option', [].slice.call(arguments));
    }

    lazy.set(this.options, key, val);
    this.emit('option', key, val);
    return this;
  },

  /**
   * Enable `key`.
   *
   * ```js
   * app.enable('a');
   * ```
   * @param {String} `key`
   * @return {Object} `Options`to enable chaining
   * @api public
   */

  enable: function(key) {
    this.option(key, true);
    return this;
  },

  /**
   * Disable `key`.
   *
   * ```js
   * app.disable('a');
   * ```
   *
   * @param {String} `key` The option to disable.
   * @return {Object} `Options`to enable chaining
   * @api public
   */

  disable: function(key) {
    this.option(key, false);
    return this;
  },

  /**
   * Check if `prop` is enabled (truthy).
   *
   * ```js
   * app.enabled('a');
   * //=> false
   *
   * app.enable('a');
   * app.enabled('a');
   * //=> true
   * ```
   *
   * @param {String} `prop`
   * @return {Boolean}
   * @api public
   */

  enabled: function(prop) {
    return Boolean(this.option(prop));
  },

  /**
   * Check if `prop` is disabled (falsey).
   *
   * ```js
   * app.disabled('a');
   * //=> true
   *
   * app.enable('a');
   * app.disabled('a');
   * //=> false
   * ```
   *
   * @param {String} `prop`
   * @return {Boolean} Returns true if `prop` is disabled.
   * @api public
   */

  disabled: function(prop) {
    return !Boolean(this.option(prop));
  },

  /**
   * Returns true if the value of `prop` is strictly `true`.
   *
   * ```js
   * app.option('a', 'b');
   * app.isTrue('a');
   * //=> false
   *
   * app.option('c', true);
   * app.isTrue('c');
   * //=> true
   *
   * app.option({a: {b: {c: true}}});
   * app.isTrue('a.b.c');
   * //=> true
   * ```
   *
   * @param {String} `prop`
   * @return {Boolean} Uses strict equality for comparison.
   * @api public
   */

  isTrue: function(prop) {
    return this.option(prop) === true;
  },

  /**
   * Returns true if the value of `key` is strictly `false`.
   *
   * ```js
   * app.option('a', null);
   * app.isFalse('a');
   * //=> false
   *
   * app.option('c', false);
   * app.isFalse('c');
   * //=> true
   *
   * app.option({a: {b: {c: false}}});
   * app.isFalse('a.b.c');
   * //=> true
   * ```
   *
   * @param {String} `prop`
   * @return {Boolean} Uses strict equality for comparison.
   * @api public
   */

  isFalse: function(prop) {
    return this.option(prop) === false;
  },

  /**
   * Return true if the value of key is either `true`
   * or `false`.
   *
   * ```js
   * app.option('a', 'b');
   * app.isBoolean('a');
   * //=> false
   *
   * app.option('c', true);
   * app.isBoolean('c');
   * //=> true
   * ```
   *
   * @param {String} `key`
   * @return {Boolean} True if `true` or `false`.
   * @api public
   */

  isBoolean: function(prop) {
    return typeof this.option(prop) === 'boolean';
  },

  /**
   * Return true if `options.hasOwnProperty(key)`
   *
   * ```js
   * app.hasOption('a');
   * //=> false
   * app.option('a', 'b');
   * app.hasOption('a');
   * //=> true
   * ```
   *
   * @param {String} `prop`
   * @return {Boolean} True if `prop` exists.
   * @api public
   */

  hasOption: function(prop) {
    if (prop.indexOf('.') === -1) {
      return this.options.hasOwnProperty(prop);
    }
    return lazy.has(this.options, prop);
  },

  /**
   * Generate an array of command line args from
   * the given `keys` or all options.
   *
   * ```js
   * // set some options
   * app.option('foo', 'bar');
   * app.option('abc', true);
   * app.option('xyz', 10);
   * app.option('one', false);
   *
   * // create command line args for all options
   * app.flags();
   * //=> ['--foo=bar', '--abc', '--xyz=10', '--no-one']
   *
   * // or specific options
   * app.flags(['foo', 'abc']);
   * //=> ['--foo=bar', '--abc']
   * ```
   *
   * @param  {Array} `keys`
   * @return {Array} Array of args
   * @api public
   */

  flags: function(keys) {
    keys = keys || Object.keys(this.options);
    return lazy.toFlags(this.options, keys);
  },

  /**
   * Map visit `method` over each object in the given array.
   *
   * @param  {String} `method`
   * @param  {Array} `arr`
   */

  visit: function(method, arr) {
    lazy.visit(this, method, arr);
    return this;
  }
});
<|endoftext|>


<commit_before>'use strict';
const path = require('path');
const os = require('os');
const fs = require('graceful-fs');
const makeDir = require('make-dir');
const xdgBasedir = require('xdg-basedir');
const writeFileAtomic = require('write-file-atomic');
const dotProp = require('dot-prop');
const uniqueString = require('unique-string');

const configDir = xdgBasedir.config || path.join(os.tmpdir(), uniqueString());
const permissionError = 'You don\'t have access to this file.';
const defaultPathMode = 0o0700;
const writeFileOptions = {mode: 0o0600};

class Configstore {
	constructor(id, defaults, opts) {
		opts = opts || {};

		const pathPrefix = opts.globalConfigPath ?
			path.join(id, 'config.json') :
			path.join('configstore', `${id}.json`);

		this.path = path.join(configDir, pathPrefix);
		this.all = Object.assign({}, defaults, this.all);
	}
	get all() {
		try {
			return JSON.parse(fs.readFileSync(this.path, 'utf8'));
		} catch (err) {
			// Create dir if it doesn't exist
			if (err.code === 'ENOENT') {
				makeDir.sync(path.dirname(this.path), defaultPathMode);
				return {};
			}

			// Improve the message of permission errors
			if (err.code === 'EACCES') {
				err.message = `${err.message}\n${permissionError}\n`;
			}

			// Empty the file if it encounters invalid JSON
			if (err.name === 'SyntaxError') {
				writeFileAtomic.sync(this.path, '', writeFileOptions);
				return {};
			}

			throw err;
		}
	}
	set all(val) {
		try {
			// Make sure the folder exists as it could have been deleted in the meantime
			makeDir.sync(path.dirname(this.path), defaultPathMode);

			writeFileAtomic.sync(this.path, JSON.stringify(val, null, '\t'), writeFileOptions);
		} catch (err) {
			// Improve the message of permission errors
			if (err.code === 'EACCES') {
				err.message = `${err.message}\n${permissionError}\n`;
			}

			throw err;
		}
	}
	get size() {
		return Object.keys(this.all || {}).length;
	}
	get(key) {
		return dotProp.get(this.all, key);
	}
	set(key, val) {
		const config = this.all;

		if (arguments.length === 1) {
			for (const k of Object.keys(key)) {
				dotProp.set(config, k, key[k]);
			}
		} else {
			dotProp.set(config, key, val);
		}

		this.all = config;
	}
	has(key) {
		return dotProp.has(this.all, key);
	}
	delete(key) {
		const config = this.all;
		dotProp.delete(config, key);
		this.all = config;
	}
	clear() {
		this.all = {};
	}
}

module.exports = Configstore;
<commit_msg>Pass options object to makeDir.sync (#55)<commit_after>'use strict';
const path = require('path');
const os = require('os');
const fs = require('graceful-fs');
const makeDir = require('make-dir');
const xdgBasedir = require('xdg-basedir');
const writeFileAtomic = require('write-file-atomic');
const dotProp = require('dot-prop');
const uniqueString = require('unique-string');

const configDir = xdgBasedir.config || path.join(os.tmpdir(), uniqueString());
const permissionError = 'You don\'t have access to this file.';
const makeDirOptions = {mode: 0o0700};
const writeFileOptions = {mode: 0o0600};

class Configstore {
	constructor(id, defaults, opts) {
		opts = opts || {};

		const pathPrefix = opts.globalConfigPath ?
			path.join(id, 'config.json') :
			path.join('configstore', `${id}.json`);

		this.path = path.join(configDir, pathPrefix);
		this.all = Object.assign({}, defaults, this.all);
	}
	get all() {
		try {
			return JSON.parse(fs.readFileSync(this.path, 'utf8'));
		} catch (err) {
			// Create dir if it doesn't exist
			if (err.code === 'ENOENT') {
				makeDir.sync(path.dirname(this.path), makeDirOptions);
				return {};
			}

			// Improve the message of permission errors
			if (err.code === 'EACCES') {
				err.message = `${err.message}\n${permissionError}\n`;
			}

			// Empty the file if it encounters invalid JSON
			if (err.name === 'SyntaxError') {
				writeFileAtomic.sync(this.path, '', writeFileOptions);
				return {};
			}

			throw err;
		}
	}
	set all(val) {
		try {
			// Make sure the folder exists as it could have been deleted in the meantime
			makeDir.sync(path.dirname(this.path), makeDirOptions);

			writeFileAtomic.sync(this.path, JSON.stringify(val, null, '\t'), writeFileOptions);
		} catch (err) {
			// Improve the message of permission errors
			if (err.code === 'EACCES') {
				err.message = `${err.message}\n${permissionError}\n`;
			}

			throw err;
		}
	}
	get size() {
		return Object.keys(this.all || {}).length;
	}
	get(key) {
		return dotProp.get(this.all, key);
	}
	set(key, val) {
		const config = this.all;

		if (arguments.length === 1) {
			for (const k of Object.keys(key)) {
				dotProp.set(config, k, key[k]);
			}
		} else {
			dotProp.set(config, key, val);
		}

		this.all = config;
	}
	has(key) {
		return dotProp.has(this.all, key);
	}
	delete(key) {
		const config = this.all;
		dotProp.delete(config, key);
		this.all = config;
	}
	clear() {
		this.all = {};
	}
}

module.exports = Configstore;
<|endoftext|>


<commit_before>'use strict';

var postcss = require('postcss');
var processResult = require('./lib/processResult');

var exitCode = 0;

module.exports = postcss.plugin('postcss-log-warnings', function(opts) {
  return function(css, result) {
    var p = new Promise(function(resolve) {
      processResult(result, resolve, opts);
    });
    p.then(function(r) {
      console.log(r);
      if (opts.throwError) exitCode = 1;
    });
    return p;
  };
});

process.on('exit', function() {
  if (exitCode) process.exit(exitCode);
});
<commit_msg>Only log if there's something to log, don't log undefined<commit_after>'use strict';

var postcss = require('postcss');
var processResult = require('./lib/processResult');

var exitCode = 0;

module.exports = postcss.plugin('postcss-log-warnings', function(opts) {
  return function(css, result) {
    var p = new Promise(function(resolve) {
      processResult(result, resolve, opts);
    });
    p.then(function(r) {
      if (r) console.log(r);
      if (opts.throwError) exitCode = 1;
    });
    return p;
  };
});

process.on('exit', function() {
  if (exitCode) process.exit(exitCode);
});
<|endoftext|>


<commit_before>//Sass compile, autoprefix, cssnano, scoping thingy
var sass_development = require('./tasks/sass_development');
var sass_production = require('./tasks/sass_production');
var linting = require('./tasks/linting');

gulp.task('sass:development', function() {
  return sass_development();
});

gulp.task('sass', ['sass-lint'], function() {
  return compileSass(gulp);
});

gulp.task('sass:production', function() {
  return sass_production();
});
<commit_msg>Setup linting dependency task.<commit_after>//Sass compile, autoprefix, cssnano, scoping thingy

var linting = require('./tasks/linting');
var sass_development = require('./tasks/sass_development');
var sass_production = require('./tasks/sass_production');

gulp.task('sass-lint', function() {
  return linting();
});

gulp.task('sass:development', ['sass-lint'], function() {
  return sass_development();
});

gulp.task('sass:production', ['sass-lint'], function() {
  return sass_production();
});

// Watch task
<|endoftext|>


<commit_before>var AWS = require('aws-sdk');
var ffmpeg = require('fluent-ffmpeg');
var q = require('q');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var gm = require('gm')
          .subClass({imageMagick: true});
var mkdirp = require('mkdirp');
var zlib = require('zlib');

var proc = require('child_process');

process.env['PATH'] = process.env['PATH'] + ':/tmp/:' + process.env['LAMBDA_TASK_ROOT']

var tmpPrefix;
var pathToBash;
var handleS3Event;
var validateKey;

if (!process.env.NODE_ENV || process.env.NODE_ENV != 'testing') {
  //production
  tmpPrefix = '/tmp/';
  pathToBash = '/tmp/gif2mp4';
  handleS3Event = require('handle-s3-event');
  validateKey = require('validate-key');
} else {
  //local
  tmpPrefix = './';
  pathToBash = './bin/gif2mp4';
  handleS3Event = require('./local_modules/handle-s3-event');
  validateKey = require('./local_modules/validate-key');
}

var s3 = new AWS.S3();

exports.handler = function(event, context) {
  process.env['FFMPEG_PATH'] = '/tmp/ffmpeg';
  process.env['FFPROBE_PATH'] = '/tmp/ffprobe';

  var promises = [];

  promises.push(handleS3Event(event))
  promises.push(validateKey);

  if (!process.env.NODE_ENV || process.env.NODE_ENV != 'testing') {
    promises.push(function(options) {
      return q.Promise(function(resolve, reject, notify) {
        console.log('Manipulating binaries.');
        proc.exec(
          'rm /tmp/*; cp /var/task/ffmpeg /tmp/.; chmod 755 /tmp/ffmpeg; cp /var/task/gif2mp4 /tmp/.; chmod 755 /tmp/gif2mp4;',
          function (error, stdout, stderr) {
            if (error) {
              reject(error)
            } else {
              resolve(options)
            }
          }
        )
      });
    })
  }

  promises.push(function(options) {
    return q.Promise(function(resolve, reject) {
      console.log('Pulling .gif from S3.');
      options.gifPath = '/tmp/' + path.basename(options.srcKey);
      console.log('the gifPath is: ' + options.gifPath);
      var params = {Bucket: options.srcBucket, Key: options.srcKey};
      var file = require('fs').createWriteStream(options.gifPath);
      var s3Req = s3.getObject(params)
      s3Req.on('complete', function() {
        resolve(options);
      })
      s3Req.on('error', function(err) {
        reject(err);
      });
      s3Req.createReadStream().pipe(file)
    })
  });

  promises.push(function(options) {
    return q.Promise(function(resolve, reject) {
      console.log('Launching script.');
      var child = proc.spawn(pathToBash, [options.gifPath]);
      child.stdout.on('data', function (data) {
        console.log("stdout: " + data);
      });
      child.stderr.on('data', function (data) {
        console.log("stderr: " + data);
      });
      child.on('exit', function (code) {
        if (code != 0) {
          reject(new Error('spawn script err'));
        } else {
          resolve(options);
        }
      });
    });
  });

  promises.push(function(options) {
    var def = q.defer();
    console.log('Ready for upload.');
    options.mp4Path = '/tmp/' + path.basename(options.gifPath, '.gif') + '-final.mp4';

    var params = {
      Bucket: options.srcBucket,
      Key: path.dirname(options.srcKey) + "/" + path.basename(options.srcKey, '.gif') + '.mp4',
      ContentType: mime.lookup(options.mp4Path)
    }

    var body = fs.createReadStream(options.mp4Path)
    var s3obj = new AWS.S3({params: params});
    s3obj.upload({Body: body})
      .on('httpUploadProgress', function(evt) {
        console.log('Upload progress: ' + (100 * evt.loaded / evt.total));
      })
      .send(function(err, data) {
        if (err) {
          def.reject(err);
        } else {
          console.log('Successful conversion and upload.');
          def.resolve(options);
        }
      });
    return def.promise;
  });

  promises.push(function(options) {
    return q.Promise(function(resolve, reject, notify) {
      console.log('Deleting uploaded mp4: ' + options.mp4Path);
      proc.exec(
        'rm ' + options.mp4Path,
        function (error, stdout, stderr) {
          if (error) {
            reject(error)
          } else {
            resolve(options)
          }
        }
      )
    });
  });

  promises.push(function(options) {
    var def = q.defer();
    console.log('Finished.');
    context.done();
    def.resolve();
    return def.promise;
  });

  promises.reduce(q.when, q())
    .fail(function(err){
      console.log('Promise rejected with err:');
      conosle.log(err);
      //doesn't try again for now, need to isolate errors from invalid keys
      context.done(null, err);
    });
};
<commit_msg>5 second delay before running bash script - make sure stream has landed... mer.<commit_after>var AWS = require('aws-sdk');
var ffmpeg = require('fluent-ffmpeg');
var q = require('q');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var gm = require('gm')
          .subClass({imageMagick: true});
var mkdirp = require('mkdirp');
var zlib = require('zlib');

var proc = require('child_process');

process.env['PATH'] = process.env['PATH'] + ':/tmp/:' + process.env['LAMBDA_TASK_ROOT']

var tmpPrefix;
var pathToBash;
var handleS3Event;
var validateKey;

if (!process.env.NODE_ENV || process.env.NODE_ENV != 'testing') {
  //production
  tmpPrefix = '/tmp/';
  pathToBash = '/tmp/gif2mp4';
  handleS3Event = require('handle-s3-event');
  validateKey = require('validate-key');
} else {
  //local
  tmpPrefix = './';
  pathToBash = './bin/gif2mp4';
  handleS3Event = require('./local_modules/handle-s3-event');
  validateKey = require('./local_modules/validate-key');
}

var s3 = new AWS.S3();

exports.handler = function(event, context) {
  process.env['FFMPEG_PATH'] = '/tmp/ffmpeg';
  process.env['FFPROBE_PATH'] = '/tmp/ffprobe';

  var promises = [];

  promises.push(handleS3Event(event))
  promises.push(validateKey);

  if (!process.env.NODE_ENV || process.env.NODE_ENV != 'testing') {
    promises.push(function(options) {
      return q.Promise(function(resolve, reject, notify) {
        console.log('Manipulating binaries.');
        proc.exec(
          'rm /tmp/*; cp /var/task/ffmpeg /tmp/.; chmod 755 /tmp/ffmpeg; cp /var/task/gif2mp4 /tmp/.; chmod 755 /tmp/gif2mp4;',
          function (error, stdout, stderr) {
            if (error) {
              reject(error)
            } else {
              resolve(options)
            }
          }
        )
      });
    })
  }

  promises.push(function(options) {
    return q.Promise(function(resolve, reject) {
      console.log('Pulling .gif from S3.');
      options.gifPath = '/tmp/' + path.basename(options.srcKey);
      console.log('the gifPath is: ' + options.gifPath);
      var params = {Bucket: options.srcBucket, Key: options.srcKey};
      var file = require('fs').createWriteStream(options.gifPath);
      var s3Req = s3.getObject(params)
      s3Req.on('complete', function() {
        resolve(options);
      })
      s3Req.on('error', function(err) {
        reject(err);
      });
      s3Req.createReadStream().pipe(file)
    })
  });

  promises.push(function(options) {
    return q.Promise(function(resolve, reject) {
      console.log('Launching script.');

      //wait 5 seconds for stream, or some bullshit
      setTimeout(function() {
        var child = proc.spawn(pathToBash, [options.gifPath]);

        child.stdout.on('data', function (data) {
          console.log("stdout: " + data);
        });
        child.stderr.on('data', function (data) {
          console.log("stderr: " + data);
        });
        child.on('exit', function (code) {
          if (code != 0) {
            reject(new Error('spawn script err'));
          } else {
            resolve(options);
          }
        });

      }, 5000);
    });
  });

  promises.push(function(options) {
    var def = q.defer();
    console.log('Ready for upload.');
    options.mp4Path = '/tmp/' + path.basename(options.gifPath, '.gif') + '-final.mp4';

    var params = {
      Bucket: options.srcBucket,
      Key: path.dirname(options.srcKey) + "/" + path.basename(options.srcKey, '.gif') + '.mp4',
      ContentType: mime.lookup(options.mp4Path)
    }

    var body = fs.createReadStream(options.mp4Path)
    var s3obj = new AWS.S3({params: params});
    s3obj.upload({Body: body})
      .on('httpUploadProgress', function(evt) {
        console.log('Upload progress: ' + (100 * evt.loaded / evt.total));
      })
      .send(function(err, data) {
        if (err) {
          def.reject(err);
        } else {
          console.log('Successful conversion and upload.');
          def.resolve(options);
        }
      });
    return def.promise;
  });

  promises.push(function(options) {
    return q.Promise(function(resolve, reject, notify) {
      console.log('Deleting uploaded mp4: ' + options.mp4Path);
      proc.exec(
        'rm ' + options.mp4Path,
        function (error, stdout, stderr) {
          if (error) {
            reject(error)
          } else {
            resolve(options)
          }
        }
      )
    });
  });

  promises.push(function(options) {
    var def = q.defer();
    console.log('Finished.');
    context.done();
    def.resolve();
    return def.promise;
  });

  promises.reduce(q.when, q())
    .fail(function(err){
      console.log('Promise rejected with err:');
      console.log(err);
      //doesn't try again for now, need to isolate errors from invalid keys
      context.done(null, err);
    });
};
<|endoftext|>


<commit_before>if (process.env.NODE_ENV !== 'development') {
  process.env.NODE_ENV = 'production'
}

var passport = require('passport')
var facebook_strategy = require('passport-facebook').Strategy

var express = require('express')
var session = require('express-session')
var session_store = require('connect-mongo')(session)
var cookie_parser = require('cookie-parser')
var body_parser = require('body-parser')
var consolidate = require('consolidate')
var getSlug = require('speakingurl')
var busboy = require('connect-busboy')
var fs = require('fs')
var md5 = require('md5')

var util = require('util')

var config = require('./config')
var image_processer = require('./imageProcesser.js')

var db = require('monk')(config.database.host + config.database.name)
var users = db.get('users')
var urlencodedParser = body_parser.urlencoded({ extended: false })

// TODO Move this out using cluster to a separate file, add more files for routes etc!
// TODO Index auth.facebook etc
// TODO set callback URLs etc in Facebook dev console
// TODO Set enableProof: true
// TODO Set fallback photo to actual link
// TODO Reauthenticate etc?
passport.use(new facebook_strategy({
    clientID: config.facebook.app_id,
    clientSecret: config.facebook.app_secret,
    callbackURL: config.facebook.callback,
    profileFields: ['id', 'name', 'displayName', 'picture.type(large)']
  },

  function (access_token, refresh_token, profile, done) {
    users.findAndModify({
      auth: {
        facebook: profile.id
      }
    }, {
      $setOnInsert: {
        auth: {
          facebook: profile.id
        },

        name: {
          display_name: profile.displayName,
          first: profile.name.givenName
        },

        info: {
          website: null,
          description: null,
        },

        photo: profile.photos ? profile.photos[0].value : '/unknown_user.png'
      }
    }, {
      new: true,
      upsert: true
    }, function (error, result) {
      done(error, {
        id: result._id,
        display_name: result.display_name,
        photo: result.photo
      })
    })
  }
))

var app = express()

// TODO Replace this with streaming json parser
app.engine('html', consolidate.ejs)
app.set('view engine', 'html')
app.set('views', __dirname + '/views')
app.use(body_parser.json())
app.use(busboy())

app.use(cookie_parser())
// TODO re-use db connection
// TODO resave/saveUnitialized
// TODO heighten cookie max time?
// TODO set secure: true later when redirecting for https etc!
// TODO use redis store?
app.use(session({
  secret: config.session_secret,
  resave: false,
  saveUninitialized: false,
  store: new session_store({
    url: config.database.host + config.database.name
  }),
  cookie: {
    maxAge: 60*60*1000,
    secure: false
  }
}))

app.use(passport.initialize())
app.use(passport.session())

if (process.env.NODE_ENV === 'development') {
  app.use(express.static(__dirname + '/public'))
  app.use('/includes', express.static(__dirname + '/includes'))
  app.use('/uploads', express.static(__dirname + '/uploads'))
}

passport.serializeUser(function (user, done) {
  done(null, user.id)
})

// TODO error handling etc
passport.deserializeUser(function (id, done) {
  users.findById(id, ['_id', 'name', 'photo', 'info'], function (error, result) {
    done(error, result)
  })
})

// TODO dynamically generate routes?

// TODO cache views etc, NODE_ENV === production?

// TODO make one default template instead of the same includes in every?
app.get('/', function (req, res) {
  var pagesdb = db.get('pages')
  if(typeof req.query.s !== 'undefined') {
    var query = {
      title: {
        $regex: req.query.s,
        $options: 'i' //i: ignore case, m: multiline, etc
      }
    }
    pagesdb.find(query, {}, function(err, doc) {
      res.render('index', { user: req.user, pages: doc, showsearch: true })
    })
  } else {
    pagesdb.find({}, function(err, doc) {
      res.render('index', { user: req.user, pages: doc, showsearch: false })
    })
  }
})

app.get('/handle', function (req, res) {
  var images = db.get('pages')
  images.find({ }, function(err, doc) {
    res.json(doc)
  })
})

app.post('/handle/post', urlencodedParser, function(req, res) {
  console.log(req.body)
  res.send('Done')
})

app.get('/logga-in', function (req, res) {

  // TODO make this a middleware or something
  if (req.isAuthenticated()) {
    // TODO get latest page we were on or something instead
    return res.redirect('/')
  }

  res.render('login', { })
})

app.get('/om', function(req, res) {
  res.render('about', { user: req.user });
})

app.get('/annonsera', function (req, res) {
  res.render('advertise', { user: req.user });
})

app.get('/riktlinjer', function (req, res) {
  res.render('guidelines', { user: req.user, hidelink: true })
});

app.get('/villkor', function (req, res) {
  res.render('terms-of-use', { user: req.user, hidelink: true })
});

app.get('/vanliga-fragor', function (req, res) {
  res.render('faq', { user: req.user })
});

app.get('/press', function (req, res) {
  res.render('press', { user: req.user })
});

app.get('/auth/facebook', passport.authenticate('facebook'), function(req, res) {})

// TODO manually handle failure?
// TODO redirect to /konto?
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), function (req, res) {
  // TODO get the page we were on when we got sent to auth instead!
  res.redirect('/')
})

app.get('/logga-ut', function (req, res) {
  req.logout()
  res.redirect('/')
})

app.get('/ajax/search', function (req, res) {
  var pagesdb = db.get('pages')
  var query = {
    title: {
      $regex: req.query.s,
      $options: 'i' //i: ignore case, m: multiline, etc
    }
  }

  pagesdb.find(query, {}, function (err, doc) {
    res.json(doc)
  })
})

app.get('/ajax/imageInfo', function (req, res) {
  if(req.query.id != undefined) {
    var imagesdb = db.get('images')
    imagesdb.find({ _id : req.query.id }, function (err, doc) {
      res.json(doc)
    })
  }
})

app.get('/:url', function (req, res, next) {
  var url = req.params.url
  var post = db.get('pages')
  post.count({ url: url }, function (err, count) {
    if(count > 0) {
      post.find({ url : url }, function (err, result) {
        users.find({ _id : result[0].user_info.id }, function(err, user_info) {
          res.render('page', { user: req.user, post: result[0], user_info: user_info[0] })
        })
      })
    } else {
      return next()
    }
  })
})

app.use(function ensure_authenticated (req, res, next) {
  if (req.isAuthenticated()) {
    return next()
  }

  res.redirect('/logga-in')
})

app.get('/konto', function (req, res) {
  res.render('konto', { user: req.user })
})

app.get('/installningar', function (req, res) {
  res.render('settings', { user: req.user, loadEditorResources: true })
})

app.post('/installningar/submit', urlencodedParser, function (req, res) {
  var id = req.user._id
  console.log(id)
  var display_name = req.body.displayName
  var website = req.body.website
  var description = req.body.description
  var users = db.get('users')
  console.log(display_name)
  users.update(
    { _id : id },
    { $set:
      { "name.display_name": display_name,
       "info.website":website,
       "info.description":description }
    }
  )
  res.send('1')
})

app.get('/mina-sidor', function (req, res) {
  var pages = db.get('pages')
  var userid = req.user.id
  pages.find({id:userid}, function(err, doc) {
    res.render('pages', { user: req.user, pages:doc })
  })
})

app.get('/ny', function (req, res) {
  res.render('new', { user: req.user })
})

app.get('/ny/publicerad', function (req, res) {
  if(typeof req.query.newpost === 'undefined') {
    res.render('post/published', { user: req.user, type: "product", hideredirect:true })
  } else {
    res.render('post/published', { user: req.user, type: "product", post_url: req.query.newpost })
  }
})

app.get('/ny/:type', function (req, res) {
  res.render('post/'+req.params.type, { user: req.user, type: req.params.type, loadEditorResources: true, loadDropzoneResources: true })
})

app.post('/submit', urlencodedParser, function (req, res) { // Controller for handling page inputs.
                                                            // ## TODO ######################################################
                                                            // # Add error handling, check and sanitize inputs              #
                                                            // # Add support for multiple sources, ingredients, steps et.c. #
                                                            // ##############################################################
  var type = req.body.type

    if(req.body.hidden) {
      var hidden = true
    } else {
      var hidden = false
    }

    var niceurl = getSlug(req.body.title, {
      // URL Settings
      separator: '-',
      maintainCase: false,
      symbols: false
    })

  var query = db.get('pages')
  if(type == 1) { // Fakta
    var data = {
      title: req.body.title,
      url: niceurl,
      type: type,
      post: {
        content: req.body.content,
        license: req.body.license,
        cover: {
          id: req.body.cover_image_id,
          filename: req.body.cover_image_filename
        },
        sources: {
          1: req.body.source
        },
      },
      user_info: {
        id: req.user._id,
        hidden: hidden
      }
    }
  } else if(type == 2) { // Recept
    var data = {
      title: req.body.title,
      url: niceurl,
      type: type,
      post: {
        content: req.body.content,
        license: req.body.license,
        license_holder: req.body.license_holder,
        cover: {
          id: req.body.cover_image_id,
          filename: req.body.cover_image_filename
        }
      },
      user_info: {
        id: req.user._id,
        hidden: hidden
      }
    }
  } else if(type == 3) { // Restaurang
    var data = {
      title: req.body.title,
      url: niceurl,
      type: type,
      post: {
        content: req.body.content,
        city: req.body.city,
        street: req.body.street,
        phone: req.body.phone,
        website: req.body.website,
        email: req.body.email,
        license: req.body.license,
        license_holder: req.body.license_holder,
        food: food,
        googlemaps: req.body.googlemaps,
        openhours: req.body.openhours,
        cover: {
          id: req.body.cover_image_id,
          filename: req.body.cover_image_filename
        },
        range: {
          lacto_ovo: req.body.lacto_ovo,
          vegan: req.body.vegan
        },
      },
      user_info: {
        id: req.user._id,
        hidden: hidden
      }
    }
  } else if(type == 4) { // Produkt assÅÅÅ
    var data = {
      title: req.body.title,
      url: niceurl,
      type: type,
      post: {
        content: req.body.content,
        license: req.body.license,
        license_holder: req.body.license_holder,
        product_type: req.body.product_type,
        veg_type: req.body.veg_type,
        cover: {
          id: req.body.cover_image_id,
          filename: req.body.cover_image_filename
        },
        sources: {
          1: req.body.source
        }
      },
      user_info: {
        id: req.user._id,
        hidden: hidden
      }
    }
  } else if(type == 5) { // Butik
    var data = {
      title: req.body.title,
      url: niceurl,
      type: type,
      post: {
        content: req.body.content,
        license: req.body.license,
        license_holder: req.body.license_holder,
        city: req.body.city,
        street: req.body.street,
        website: req.body.website,
        googlemaps: req.body.googlemaps,
        openhours: req.body.openhours,
        cover: {
          id: req.body.cover_image_id,
          filename: req.body.cover_image_filename
        }
      }
    }
  } else {
    res.redirect('/ny')
  }
    query.insert(data, function(err, doc) {
      if(err) throw err
    })
    res.redirect('/ny/publicerad/?newpost='+niceurl)
})

app.post('/submit/file', function(req, res) {
  var fstream
    req.pipe(req.busboy)
    req.busboy.on('file', function (fieldname, file, filename) {
        var images = db.get('images')
        images.count({ }, function (err, num_rows) {
          uHash = md5(num_rows + 1)
          uFilename = uHash.substring(0, 11)
          images.insert({ id:num_rows + 1, filename: uFilename, active: false, deleted: false, "user_info":{ id: req.user._id } }, function(err, doc) {
            if(err) throw err
            fstream = fs.createWriteStream(__dirname + '/uploads/' + uFilename + '_original.jpg')
            file.pipe(fstream)
            var resize = image_processer.resize(uFilename, 1200, 630)
            if(resize == true) {
              fstream.on('close', function () {
                res.send(doc._id)
              })
            }
          })
        })
    })
})

// TODO 'uncaughtException' as well? See what happens if DB goes down etc
app.use(function error_handler (error, req, res, next) {
  // TODO better error page
  console.error(error.stack)
  res.status(500)
  res.send('An error occured!')
})

app.listen(process.env.PORT || config.port, config.address)<commit_msg>Fixes<commit_after>if (process.env.NODE_ENV !== 'development') {
  process.env.NODE_ENV = 'production'
}

var passport = require('passport')
var facebook_strategy = require('passport-facebook').Strategy

var express = require('express')
var session = require('express-session')
var session_store = require('connect-mongo')(session)
var cookie_parser = require('cookie-parser')
var body_parser = require('body-parser')
var consolidate = require('consolidate')
var getSlug = require('speakingurl')
var busboy = require('connect-busboy')
var fs = require('fs')
var md5 = require('md5')

var util = require('util')

var config = require('./config')
var image_processer = require('./imageProcesser.js')

var db = require('monk')(config.database.host + config.database.name)
var users = db.get('users')
var urlencodedParser = body_parser.urlencoded({ extended: false })

// TODO Move this out using cluster to a separate file, add more files for routes etc!
// TODO Index auth.facebook etc
// TODO set callback URLs etc in Facebook dev console
// TODO Set enableProof: true
// TODO Set fallback photo to actual link
// TODO Reauthenticate etc?
passport.use(new facebook_strategy({
    clientID: config.facebook.app_id,
    clientSecret: config.facebook.app_secret,
    callbackURL: config.facebook.callback,
    profileFields: ['id', 'name', 'displayName', 'picture.type(large)']
  },

  function (access_token, refresh_token, profile, done) {
    users.findAndModify({
      auth: {
        facebook: profile.id
      }
    }, {
      $setOnInsert: {
        auth: {
          facebook: profile.id
        },

        name: {
          display_name: profile.displayName,
          first: profile.name.givenName
        },

        info: {
          website: null,
          description: null,
        },

        photo: profile.photos ? profile.photos[0].value : '/unknown_user.png'
      }
    }, {
      new: true,
      upsert: true
    }, function (error, result) {
      done(error, {
        id: result._id,
        display_name: result.display_name,
        photo: result.photo
      })
    })
  }
))

var app = express()

// TODO Replace this with streaming json parser
app.engine('html', consolidate.ejs)
app.set('view engine', 'html')
app.set('views', __dirname + '/views')
app.use(body_parser.json())
app.use(busboy())

app.use(cookie_parser())
// TODO re-use db connection
// TODO resave/saveUnitialized
// TODO heighten cookie max time?
// TODO set secure: true later when redirecting for https etc!
// TODO use redis store?
app.use(session({
  secret: config.session_secret,
  resave: false,
  saveUninitialized: false,
  store: new session_store({
    url: config.database.host + config.database.name
  }),
  cookie: {
    maxAge: 60*60*1000,
    secure: false
  }
}))

app.use(passport.initialize())
app.use(passport.session())

if (process.env.NODE_ENV === 'development') {
  app.use(express.static(__dirname + '/public'))
  app.use('/includes', express.static(__dirname + '/includes'))
  app.use('/uploads', express.static(__dirname + '/uploads'))
}

passport.serializeUser(function (user, done) {
  done(null, user.id)
})

// TODO error handling etc
passport.deserializeUser(function (id, done) {
  users.findById(id, ['_id', 'name', 'photo', 'info'], function (error, result) {
    done(error, result)
  })
})

// TODO dynamically generate routes?

// TODO cache views etc, NODE_ENV === production?

// TODO make one default template instead of the same includes in every?
app.get('/', function (req, res) {
  var pagesdb = db.get('pages')
  if(typeof req.query.s !== 'undefined') {
    var query = {
      title: {
        $regex: req.query.s,
        $options: 'i' //i: ignore case, m: multiline, etc
      }
    }
    pagesdb.find(query, {}, function(err, doc) {
      res.render('index', { user: req.user, pages: doc, showsearch: true })
    })
  } else {
    pagesdb.find({}, function(err, doc) {
      res.render('index', { user: req.user, pages: doc, showsearch: false })
    })
  }
})

app.get('/handle', function (req, res) {
  var images = db.get('pages')
  images.find({ }, function(err, doc) {
    res.json(doc)
  })
})

app.post('/handle/post', urlencodedParser, function(req, res) {
  console.log(req.body)
  res.send('Done')
})

app.get('/logga-in', function (req, res) {

  // TODO make this a middleware or something
  if (req.isAuthenticated()) {
    // TODO get latest page we were on or something instead
    return res.redirect('/')
  }

  res.render('login', { })
})

app.get('/om', function(req, res) {
  res.render('about', { user: req.user });
})

app.get('/annonsera', function (req, res) {
  res.render('advertise', { user: req.user });
})

app.get('/riktlinjer', function (req, res) {
  res.render('guidelines', { user: req.user, hidelink: true })
});

app.get('/villkor', function (req, res) {
  res.render('terms-of-use', { user: req.user, hidelink: true })
});

app.get('/vanliga-fragor', function (req, res) {
  res.render('faq', { user: req.user })
});

app.get('/press', function (req, res) {
  res.render('press', { user: req.user })
});

app.get('/auth/facebook', passport.authenticate('facebook'), function(req, res) {})

// TODO manually handle failure?
// TODO redirect to /konto?
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), function (req, res) {
  // TODO get the page we were on when we got sent to auth instead!
  res.redirect('/')
})

app.get('/logga-ut', function (req, res) {
  req.logout()
  res.redirect('/')
})

app.get('/ajax/search', function (req, res) {
  var pagesdb = db.get('pages')
  var query = {
    title: {
      $regex: req.query.s,
      $options: 'i' //i: ignore case, m: multiline, etc
    }
  }

  pagesdb.find(query, {}, function (err, doc) {
    res.json(doc)
  })
})

app.get('/ajax/imageInfo', function (req, res) {
  if(req.query.id != undefined) {
    var imagesdb = db.get('images')
    imagesdb.find({ _id : req.query.id }, function (err, doc) {
      res.json(doc)
    })
  }
})

app.get('/:url', function (req, res, next) {
  var url = req.params.url
  var post = db.get('pages')
  post.count({ url: url }, function (err, count) {
    if(count > 0) {
      post.find({ url : url }, function (err, result) {
        users.find({ _id : result[0].user_info.id }, function(err, user_info) {
          res.render('page', { user: req.user, post: result[0], user_info: user_info[0] })
        })
      })
    } else {
      return next()
    }
  })
})

app.use(function ensure_authenticated (req, res, next) {
  if (req.isAuthenticated()) {
    return next()
  }

  res.redirect('/logga-in')
})

app.get('/konto', function (req, res) {
  res.render('konto', { user: req.user })
})

app.get('/installningar', function (req, res) {
  res.render('settings', { user: req.user, loadEditorResources: true })
})

app.post('/installningar/submit', urlencodedParser, function (req, res) {
  var id = req.user._id
  console.log(id)
  var display_name = req.body.displayName
  var website = req.body.website
  var description = req.body.description
  var users = db.get('users')
  console.log(display_name)
  users.update(
    { _id : id },
    { $set:
      { "name.display_name": display_name,
       "info.website":website,
       "info.description":description }
    }
  )
  res.send('1')
})

app.get('/mina-sidor', function (req, res) {
  var pages = db.get('pages')
  var userid = req.user.id
  pages.find({id:userid}, function(err, doc) {
    res.render('pages', { user: req.user, pages:doc })
  })
})

app.get('/ny', function (req, res) {
  res.render('new', { user: req.user })
})

app.get('/ny/publicerad', function (req, res) {
  if(typeof req.query.newpost === 'undefined') {
    res.render('post/published', { user: req.user, type: "product", hideredirect:true })
  } else {
    res.render('post/published', { user: req.user, type: "product", post_url: req.query.newpost })
  }
})

app.get('/ny/:type', function (req, res) {
  res.render('post/'+req.params.type, { user: req.user, type: req.params.type, loadEditorResources: true, loadDropzoneResources: true })
})

app.post('/submit', urlencodedParser, function (req, res) { // Controller for handling page inputs.
                                                            // ## TODO ######################################################
                                                            // # Add error handling, check and sanitize inputs              #
                                                            // # Add support for multiple sources, ingredients, steps et.c. #
                                                            // ##############################################################
  var type = req.body.type

    if(req.body.hidden) {
      var hidden = true
    } else {
      var hidden = false
    }

    var niceurl = getSlug(req.body.title, {
      // URL Settings
      separator: '-',
      maintainCase: false,
      symbols: false
    })

  var query = db.get('pages')
  if(type == 1) { // Fakta
    var data = {
      title: req.body.title,
      url: niceurl,
      type: type,
      post: {
        content: req.body.content,
        license: req.body.license,
        cover: {
          id: req.body.cover_image_id,
          filename: req.body.cover_image_filename
        },
        sources: {
          1: req.body.source
        },
      },
      user_info: {
        id: req.user._id,
        hidden: hidden
      }
    }
  } else if(type == 2) { // Recept
    var data = {
      title: req.body.title,
      url: niceurl,
      type: type,
      post: {
        content: req.body.content,
        license: req.body.license,
        license_holder: req.body.license_holder,
        cover: {
          id: req.body.cover_image_id,
          filename: req.body.cover_image_filename
        }
      },
      user_info: {
        id: req.user._id,
        hidden: hidden
      }
    }
  } else if(type == 3) { // Restaurang
    var data = {
      title: req.body.title,
      url: niceurl,
      type: type,
      post: {
        content: req.body.content,
        city: req.body.city,
        street: req.body.street,
        phone: req.body.phone,
        website: req.body.website,
        email: req.body.email,
        license: req.body.license,
        license_holder: req.body.license_holder,
        food: food,
        googlemaps: req.body.googlemaps,
        openhours: req.body.openhours,
        cover: {
          id: req.body.cover_image_id,
          filename: req.body.cover_image_filename
        },
        range: {
          lacto_ovo: req.body.lacto_ovo,
          vegan: req.body.vegan
        },
      },
      user_info: {
        id: req.user._id,
        hidden: hidden
      }
    }
  } else if(type == 4) { // Produkt
    var data = {
      title: req.body.title,
      url: niceurl,
      type: type,
      post: {
        content: req.body.content,
        license: req.body.license,
        license_holder: req.body.license_holder,
        veg_type: req.body.veg_type,
        product_type: req.body.product_type,
        cover: {
          id: req.body.cover_image_id,
          filename: req.body.cover_image_filename
        },
        sources: {
          1: req.body.source
        }
      },
      user_info: {
        id: req.user._id,
        hidden: hidden
      }
    }
  } else if(type == 5) { // Butik
    var data = {
      title: req.body.title,
      url: niceurl,
      type: type,
      post: {
        content: req.body.content,
        license: req.body.license,
        license_holder: req.body.license_holder,
        city: req.body.city,
        street: req.body.street,
        website: req.body.website,
        googlemaps: req.body.googlemaps,
        openhours: req.body.openhours,
        cover: {
          id: req.body.cover_image_id,
          filename: req.body.cover_image_filename
        }
      }
    }
  } else {
    res.redirect('/ny')
  }
    query.insert(data, function(err, doc) {
      if(err) throw err
    })
    res.redirect('/ny/publicerad/?newpost='+niceurl)
})

app.post('/submit/file', function(req, res) {
  var fstream
    req.pipe(req.busboy)
    req.busboy.on('file', function (fieldname, file, filename) {
        var images = db.get('images')
        images.count({ }, function (err, num_rows) {
          uHash = md5(num_rows + 1)
          uFilename = uHash.substring(0, 11)
          images.insert({ id:num_rows + 1, filename: uFilename, active: false, deleted: false, "user_info":{ id: req.user._id } }, function(err, doc) {
            if(err) throw err
            fstream = fs.createWriteStream(__dirname + '/uploads/' + uFilename + '_original.jpg')
            file.pipe(fstream)
            var resize = image_processer.resize(uFilename, 1200, 630)
            if(resize == true) {
              fstream.on('close', function () {
                res.send(doc._id)
              })
            }
          })
        })
    })
})

// TODO 'uncaughtException' as well? See what happens if DB goes down etc
app.use(function error_handler (error, req, res, next) {
  // TODO better error page
  console.error(error.stack)
  res.status(500)
  res.send('An error occured!')
})

app.listen(process.env.PORT || config.port, config.address)<|endoftext|>


<commit_before>module.exports = decodeTorrentFile
module.exports.decode = decodeTorrentFile
module.exports.encode = encodeTorrentFile

var bencode = require('bencode')
var path = require('path')
var sha1 = require('simple-sha1')
var uniq = require('uniq')

/**
 * Parse a torrent. Throws an exception if the torrent is missing required fields.
 * @param  {Buffer|Object} torrent
 * @return {Object}        parsed torrent
 */
function decodeTorrentFile (torrent) {
  if (Buffer.isBuffer(torrent)) {
    torrent = bencode.decode(torrent)
  }

  // sanity check
  ensure(torrent.info, 'info')
  ensure(torrent.info['name.utf-8'] || torrent.info.name, 'info.name')
  ensure(torrent.info['piece length'], 'info[\'piece length\']')
  ensure(torrent.info.pieces, 'info.pieces')

  if (torrent.info.files) {
    torrent.info.files.forEach(function (file) {
      ensure(typeof file.length === 'number', 'info.files[0].length')
      ensure(file['path.utf-8'] || file.path, 'info.files[0].path')
    })
  } else {
    ensure(typeof torrent.info.length === 'number', 'info.length')
  }

  var result = {}
  result.info = torrent.info
  result.infoBuffer = bencode.encode(torrent.info)
  result.infoHash = sha1.sync(result.infoBuffer)
  result.infoHashBuffer = Buffer.from(result.infoHash, 'hex')

  result.name = (torrent.info['name.utf-8'] || torrent.info.name).toString()

  if (torrent.info.private !== undefined) result.private = !!torrent.info.private

  if (torrent['creation date']) result.created = new Date(torrent['creation date'] * 1000)
  if (torrent['created by']) result.createdBy = torrent['created by'].toString()

  if (Buffer.isBuffer(torrent.comment)) result.comment = torrent.comment.toString()

  // announce and announce-list will be missing if metadata fetched via ut_metadata
  result.announce = []
  if (torrent['announce-list'] && torrent['announce-list'].length) {
    torrent['announce-list'].forEach(function (urls) {
      urls.forEach(function (url) {
        result.announce.push(url.toString())
      })
    })
  } else if (torrent.announce) {
    result.announce.push(torrent.announce.toString())
  }

  // handle url-list (BEP19 / web seeding)
  if (Buffer.isBuffer(torrent['url-list'])) {
    // some clients set url-list to empty string
    torrent['url-list'] = torrent['url-list'].length > 0
      ? [ torrent['url-list'] ]
      : []
  }
  result.urlList = (torrent['url-list'] || []).map(function (url) {
    return url.toString()
  })

  uniq(result.announce)
  uniq(result.urlList)

  var files = torrent.info.files || [ torrent.info ]
  result.files = files.map(function (file, i) {
    var parts = [].concat(result.name, file['path.utf-8'] || file.path || []).map(function (p) {
      return p.toString()
    })
    return {
      path: path.join.apply(null, [path.sep].concat(parts)).slice(1),
      name: parts[parts.length - 1],
      length: file.length,
      offset: files.slice(0, i).reduce(sumLength, 0)
    }
  })

  result.length = files.reduce(sumLength, 0)

  var lastFile = result.files[result.files.length - 1]

  result.pieceLength = torrent.info['piece length']
  result.lastPieceLength = ((lastFile.offset + lastFile.length) % result.pieceLength) || result.pieceLength
  result.pieces = splitPieces(torrent.info.pieces)

  return result
}

/**
 * Convert a parsed torrent object back into a .torrent file buffer.
 * @param  {Object} parsed parsed torrent
 * @return {Buffer}
 */
function encodeTorrentFile (parsed) {
  var torrent = {
    info: parsed.info
  }

  torrent['announce-list'] = (parsed.announce || []).map(function (url) {
    if (!torrent.announce) torrent.announce = url
    url = Buffer.from(url, 'utf8')
    return [ url ]
  })

  torrent['url-list'] = parsed.urlList || []

  if (parsed.private !== undefined) {
    torrent['private'] = parsed.private
  }

  if (parsed.created) {
    torrent['creation date'] = (parsed.created.getTime() / 1000) | 0
  }

  if (parsed.createdBy) {
    torrent['created by'] = parsed.createdBy
  }

  if (parsed.comment) {
    torrent.comment = parsed.comment
  }

  return bencode.encode(torrent)
}

function sumLength (sum, file) {
  return sum + file.length
}

function splitPieces (buf) {
  var pieces = []
  for (var i = 0; i < buf.length; i += 20) {
    pieces.push(buf.slice(i, i + 20).toString('hex'))
  }
  return pieces
}

function ensure (bool, fieldName) {
  if (!bool) throw new Error('Torrent is missing required field: ' + fieldName)
}
<commit_msg>be stricter about only setting private to true/false<commit_after>module.exports = decodeTorrentFile
module.exports.decode = decodeTorrentFile
module.exports.encode = encodeTorrentFile

var bencode = require('bencode')
var path = require('path')
var sha1 = require('simple-sha1')
var uniq = require('uniq')

/**
 * Parse a torrent. Throws an exception if the torrent is missing required fields.
 * @param  {Buffer|Object} torrent
 * @return {Object}        parsed torrent
 */
function decodeTorrentFile (torrent) {
  if (Buffer.isBuffer(torrent)) {
    torrent = bencode.decode(torrent)
  }

  // sanity check
  ensure(torrent.info, 'info')
  ensure(torrent.info['name.utf-8'] || torrent.info.name, 'info.name')
  ensure(torrent.info['piece length'], 'info[\'piece length\']')
  ensure(torrent.info.pieces, 'info.pieces')

  if (torrent.info.files) {
    torrent.info.files.forEach(function (file) {
      ensure(typeof file.length === 'number', 'info.files[0].length')
      ensure(file['path.utf-8'] || file.path, 'info.files[0].path')
    })
  } else {
    ensure(typeof torrent.info.length === 'number', 'info.length')
  }

  var result = {}
  result.info = torrent.info
  result.infoBuffer = bencode.encode(torrent.info)
  result.infoHash = sha1.sync(result.infoBuffer)
  result.infoHashBuffer = Buffer.from(result.infoHash, 'hex')

  result.name = (torrent.info['name.utf-8'] || torrent.info.name).toString()

  if (torrent.info.private !== undefined) result.private = !!torrent.info.private

  if (torrent['creation date']) result.created = new Date(torrent['creation date'] * 1000)
  if (torrent['created by']) result.createdBy = torrent['created by'].toString()

  if (Buffer.isBuffer(torrent.comment)) result.comment = torrent.comment.toString()

  // announce and announce-list will be missing if metadata fetched via ut_metadata
  result.announce = []
  if (torrent['announce-list'] && torrent['announce-list'].length) {
    torrent['announce-list'].forEach(function (urls) {
      urls.forEach(function (url) {
        result.announce.push(url.toString())
      })
    })
  } else if (torrent.announce) {
    result.announce.push(torrent.announce.toString())
  }

  // handle url-list (BEP19 / web seeding)
  if (Buffer.isBuffer(torrent['url-list'])) {
    // some clients set url-list to empty string
    torrent['url-list'] = torrent['url-list'].length > 0
      ? [ torrent['url-list'] ]
      : []
  }
  result.urlList = (torrent['url-list'] || []).map(function (url) {
    return url.toString()
  })

  uniq(result.announce)
  uniq(result.urlList)

  var files = torrent.info.files || [ torrent.info ]
  result.files = files.map(function (file, i) {
    var parts = [].concat(result.name, file['path.utf-8'] || file.path || []).map(function (p) {
      return p.toString()
    })
    return {
      path: path.join.apply(null, [path.sep].concat(parts)).slice(1),
      name: parts[parts.length - 1],
      length: file.length,
      offset: files.slice(0, i).reduce(sumLength, 0)
    }
  })

  result.length = files.reduce(sumLength, 0)

  var lastFile = result.files[result.files.length - 1]

  result.pieceLength = torrent.info['piece length']
  result.lastPieceLength = ((lastFile.offset + lastFile.length) % result.pieceLength) || result.pieceLength
  result.pieces = splitPieces(torrent.info.pieces)

  return result
}

/**
 * Convert a parsed torrent object back into a .torrent file buffer.
 * @param  {Object} parsed parsed torrent
 * @return {Buffer}
 */
function encodeTorrentFile (parsed) {
  var torrent = {
    info: parsed.info
  }

  torrent['announce-list'] = (parsed.announce || []).map(function (url) {
    if (!torrent.announce) torrent.announce = url
    url = Buffer.from(url, 'utf8')
    return [ url ]
  })

  torrent['url-list'] = parsed.urlList || []

  if (parsed.private === true || parsed.private === false) {
    torrent['private'] = parsed.private
  }

  if (parsed.created) {
    torrent['creation date'] = (parsed.created.getTime() / 1000) | 0
  }

  if (parsed.createdBy) {
    torrent['created by'] = parsed.createdBy
  }

  if (parsed.comment) {
    torrent.comment = parsed.comment
  }

  return bencode.encode(torrent)
}

function sumLength (sum, file) {
  return sum + file.length
}

function splitPieces (buf) {
  var pieces = []
  for (var i = 0; i < buf.length; i += 20) {
    pieces.push(buf.slice(i, i + 20).toString('hex'))
  }
  return pieces
}

function ensure (bool, fieldName) {
  if (!bool) throw new Error('Torrent is missing required field: ' + fieldName)
}
<|endoftext|>


<commit_before>var fs = require('fs');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require("express");
var mkdirp = require('mkdirp');
var map_data = JSON.parse(fs.readFileSync(__dirname + "/data/map", "utf8"));
var port = 25500; // port for server to run on
app.get('/', function(req, res){
  res.sendFile(__dirname + '/static/index.html');
});
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
    next();
});

app.use('/external/', express.static(__dirname + "/static/"));
io.on('connection', function(socket){

});

io.on('connection', function(socket){

  socket.on('disconnect', function(){
    console.log("SERVER: a user disconnected");
  });
});

function countInArray(array, what) {
    var count = 0;
    for (var i = 0; i < array.length; i++) {
        if (array[i] === what) {
            count++;
        }
    }
    return count;
}

io.on('connection', function(socket){
  socket.on('move', function(msg){
    var claim = msg.split(",");
    console.log("SERVER: claimed land: " + claim[0] + "," + claim[1] + " by " + claim[2]);
    var tdir = __dirname + "/data/" + claim[2] + "/";
    var color;
    try {
    var tx = fs.readFileSync(tdir + "x", "utf8");
    var ty = fs.readFileSync(tdir + "y", "utf8");
    color = fs.readFileSync(tdir + "color", "utf8");
  } catch (err) {}
    fs.writeFile(tdir + "x", claim[0]);
    fs.writeFile(tdir + "y", claim[1]);
    io.emit('new-claim', claim[0] + "," + claim[1] + ', "' + color + '"');
    var ocl;
    try {
    ocl = fs.readFileSync(__dirname + "/lb/" + color);
  } catch(err) {
    if (err.code === 'ENOENT') {
    ocl = 0;
    fs.writeFile(__dirname + "/lb/" + color, "0");
  }
  }

  if (isNaN(ocl)) {
    ocl = countInArray(map_data, color);
    fs.writeFile(__dirname + "/lb/" + color, ocl);
  }
    var rem = parseInt(ocl) + 1;
    fs.writeFile(__dirname + "/lb/" + color, rem);
    removal = claim[0] + "x" + claim[1];
    var rcc = [];
    rcc = map_data.find(loc);
    console.log(rcc);
    if (rcc != null) {
    var ocl;
    try {
  ocl = fs.readFileSync(__dirname + "/lb/" + rcc[1]);
} catch(err) {
  if (err.code === 'ENOENT') {
  fs.writeFile(__dirname + "/lb/" + rcc[1], "0");
  ocl = 0;
}
}

  if (isNaN(ocl)) {
    ocl = countInArray(map_data, color);
    fs.writeFile(__dirname + "/lb/" + rcc[1], ocl);
  }
    var rem = parseInt(ocl) - 1;
    fs.writeFile(__dirname + "/lb/" + rcc[1], rem);
  }

    map_data = map_data.filter(function(item) {
  return (item[0] !== claim[0] + "x" + claim[1]) // Only keep arrays that don't begin with 5x3
})
    claim = [  parseInt(claim[0]) + "x" + parseInt(claim[1]) , color]
    map_data = map_data.concat([[claim[0],claim[1]]]);
  });
});

function loc(element) {
  return element[0] == removal;
}
var removal;

io.on('connection', function(socket){
  socket.on('new-join', function(message) {
	console.log("SERVER: user join: " + message);

	var tdir = __dirname + "/data/" + message + "/";
	var x,y,c;
  	try {
  		x= fs.readFileSync(tdir + "x", "utf8");
  		y= fs.readFileSync(tdir + "y", "utf8");
  		c= fs.readFileSync(tdir + "color", "utf8");
  	} catch (err) {}
  	console.log("SERVER: sending info to user " + message + ": " +  x + "," + y + "," + c);
  	this.emit("info", x + "," + y + "," + c);
    this.emit("gmap", map_data);

	});
});

function remove(arr, what) {
    var found = arr.indexOf(what);

    while (found !== -1) {
        arr.splice(found, 1);
        found = arr.indexOf(what);

    }
}

function file_get_cont(name) {
  var chunk, data;
  var readStream = fs.createReadStream(name, 'utf8');

readStream.on('data', function(chunk) {
    data += chunk;
}).on('end', function() {
    return data;
});
}
function getRandomInt(min, max) {
	return Math.floor(Math.random() * (max-min + 1)) + min;
}

io.on('connection', function(socket){
  socket.on('new-user', function(message) {
	var c = new Date();
	var ms = c.getTime();
	mkdirp(__dirname + "/data/" + ms, function(err) {
	});
	var tdir = __dirname + "/data/" + ms + "/";
  var genc = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
	fs.writeFile(tdir + "color", genc);
  fs.writeFile(__dirname + "/lb/" + genc, "0");
	fs.writeFile(tdir + "x", Math.round(getRandomInt(-1000,1000)));
	fs.writeFile(tdir + "y", Math.round(getRandomInt(-1000,1000)));
	fs.writeFile(tdir + "claimed", "0");
	this.emit("new-info", ms);
	console.log("SERVER: new user: " + ms);
	});
});

setInterval(function() {
fs.writeFile(__dirname + "/data/map", JSON.stringify(map_data));
console.log("SERVER: map backed up");
}, 30000);

http.listen(port, function(){
  console.log('SERVER: initialized. listening on port ' + port);
});

io.on('connection', function(socket){
  socket.on('req-map', function(message) {
    this.emit("gmap", map_data);

	});
});

function Comparator(a, b) {
  if (a[1] < b[1]) return -1;
  if (a[1] > b[1]) return 1;
  return 0;
}

setInterval(function() {
  var files = fs.readdirSync(__dirname + "/lb/");
var c1 = [];
files.forEach(function(entry) {
var cos, cos2;
  try {
  cos = entry;
  cos2 = fs.readFileSync(__dirname + "/lb/" + entry, "utf8");
} catch (err) {}

    c1 = c1.concat([[cos2.replace(/\n|\r/g, ""), cos]]);
});

c2 = c1.sort(Comparator);

io.emit("leader", c2);
}, 5000);
<commit_msg>working scoreboard<commit_after>var fs = require('fs');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require("express");
var mkdirp = require('mkdirp');
var map_data = JSON.parse(fs.readFileSync(__dirname + "/data/map", "utf8"));
var port = 25500; // port for server to run on
app.get('/', function(req, res){
  res.sendFile(__dirname + '/static/index.html');
});
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
    next();
});

app.use('/external/', express.static(__dirname + "/static/"));
io.on('connection', function(socket){

});

io.on('connection', function(socket){

  socket.on('disconnect', function(){
    console.log("SERVER: a user disconnected");
  });
});

function countInArray(array, what) {
    var count = 0;
    for (var i = 0; i < array.length; i++) {
        if (array[i] === what) {
            count++;
        }
    }
    return count;
}

io.on('connection', function(socket){
  socket.on('move', function(msg){
    var claim = msg.split(",");
    console.log("SERVER: claimed land: " + claim[0] + "," + claim[1] + " by " + claim[2]);
    var tdir = __dirname + "/data/" + claim[2] + "/";
    var color;
    try {
    var tx = fs.readFileSync(tdir + "x", "utf8");
    var ty = fs.readFileSync(tdir + "y", "utf8");
    color = fs.readFileSync(tdir + "color", "utf8");
  } catch (err) {}
    fs.writeFile(tdir + "x", claim[0]);
    fs.writeFile(tdir + "y", claim[1]);
    io.emit('new-claim', claim[0] + "," + claim[1] + ', "' + color + '"');
    map_data = map_data.filter(function(item) {
  return (item[0] !== claim[0] + "x" + claim[1]) // Only keep arrays that don't begin with 5x3
})
    claim = [  parseInt(claim[0]) + "x" + parseInt(claim[1]) , color]
    map_data = map_data.concat([[claim[0],claim[1]]]);
  });
});

function loc(element) {
  return element[0] == removal;
}
var removal;

io.on('connection', function(socket){
  socket.on('new-join', function(message) {
	console.log("SERVER: user join: " + message);

	var tdir = __dirname + "/data/" + message + "/";
	var x,y,c;
  	try {
  		x= fs.readFileSync(tdir + "x", "utf8");
  		y= fs.readFileSync(tdir + "y", "utf8");
  		c= fs.readFileSync(tdir + "color", "utf8");
  	} catch (err) {}
  	console.log("SERVER: sending info to user " + message + ": " +  x + "," + y + "," + c);
  	this.emit("info", x + "," + y + "," + c);
    this.emit("gmap", map_data);

	});
});

function remove(arr, what) {
    var found = arr.indexOf(what);

    while (found !== -1) {
        arr.splice(found, 1);
        found = arr.indexOf(what);

    }
}

function file_get_cont(name) {
  var chunk, data;
  var readStream = fs.createReadStream(name, 'utf8');

readStream.on('data', function(chunk) {
    data += chunk;
}).on('end', function() {
    return data;
});
}
function getRandomInt(min, max) {
	return Math.floor(Math.random() * (max-min + 1)) + min;
}

io.on('connection', function(socket){
  socket.on('new-user', function(message) {
	var c = new Date();
	var ms = c.getTime();
	mkdirp(__dirname + "/data/" + ms, function(err) {
	});
	var tdir = __dirname + "/data/" + ms + "/";
  var genc = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
	fs.writeFile(tdir + "color", genc);
  fs.writeFile(__dirname + "/lb/" + genc, "0");
	fs.writeFile(tdir + "x", Math.round(getRandomInt(-1000,1000)));
	fs.writeFile(tdir + "y", Math.round(getRandomInt(-1000,1000)));
	fs.writeFile(tdir + "claimed", "0");
	this.emit("new-info", ms);
	console.log("SERVER: new user: " + ms);
	});
});

setInterval(function() {
fs.writeFile(__dirname + "/data/map", JSON.stringify(map_data));
console.log("SERVER: map backed up");
}, 30000);

http.listen(port, function(){
  console.log('SERVER: initialized. listening on port ' + port);
});

io.on('connection', function(socket){
  socket.on('req-map', function(message) {
    this.emit("gmap", map_data);

	});
});

function Comparator(a, b) {
  if (a[1] < b[1]) return -1;
  if (a[1] > b[1]) return 1;
  return 0;
}

function inArray(arr) { // from http://jsfiddle.net/simevidas/bnACW/ i changed the name of the func though
    var a = [], b = [], prev;

    arr.sort();
    for ( var i = 0; i < arr.length; i++ ) {
        if ( arr[i] !== prev ) {
            a.push(arr[i]);
            b.push(1);
        } else {
            b[b.length-1]++;
        }
        prev = arr[i];
    }

    return [a, b];
}

setInterval(function() {
var cc = map_data.toString();
cc = cc.split(",");
for (var i = 0; i <= cc.length; i += 1)
    cc.splice(i, 1);

var res = inArray(cc);
var occur = res[1];
var found = res[0];

var c1 = [];
for (i = 0; i <= occur.length - 1; i++) {
    c1 = c1.concat([[occur[i], found[i]]]);
}

c2 = c1.sort(Comparator);
c2 = c2.slice(0,10);
io.emit("leader", c2);
}, 5000);
<|endoftext|>


<commit_before>/*!
 * base-store <https://github.com/jonschlinkert/base-store>
 *
 * Copyright (c) 2015-2016, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

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

module.exports = function(name, config) {
  if (typeof name !== 'string') {
    config = name;
    name = undefined;
  }

  return function(app) {
    if (this.isRegistered('store')) return;

    if (typeof name === 'undefined') {
      name = utils.project(process.cwd());
    }

    var opts = utils.extend({}, config, app.options.store);
    this.define('store', utils.store(name, opts));

    /**
     * Bubble up specific events to `app`
     */

    this.store.on('set', function(key, val) {
      app.emit('store.set', key, val);
      app.emit('store', 'set', key, val);
    });

    this.store.on('get', function(key, val) {
      app.emit('store.get', key, val);
      app.emit('store', 'get', key, val);
    });

    this.store.on('del', function(key, val) {
      app.emit('store.del', key, val);
      app.emit('store', 'del', key, val);
    });
  };
};
<commit_msg>return the plugin, improve validation logic<commit_after>/*!
 * base-store <https://github.com/jonschlinkert/base-store>
 *
 * Copyright (c) 2015-2016, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

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

module.exports = function(name, config) {
  if (typeof name !== 'string') {
    config = name;
    name = undefined;
  }

  return function plugin(app) {
    if (!isValidInstance(app)) return;

    if (typeof name === 'undefined') {
      name = utils.project(process.cwd());
    }

    var opts = utils.extend({}, config, app.options.store);
    this.define('store', utils.store(name, opts));

    /**
     * Bubble up specific events to `app`
     */

    this.store.on('set', function(key, val) {
      app.emit('store.set', key, val);
      app.emit('store', 'set', key, val);
    });

    this.store.on('get', function(key, val) {
      app.emit('store.get', key, val);
      app.emit('store', 'get', key, val);
    });

    this.store.on('del', function(key, val) {
      app.emit('store.del', key, val);
      app.emit('store', 'del', key, val);
    });

    return plugin;
  };
};

function isValidInstance(app) {
  var fn = app.options.validatePlugin;
  if (typeof fn === 'function' && !fn(app)) {
    return false;
  }
  if (app.isRegistered('base-store')) {
    return false;
  }
  if (app.isCollection || app.isView) {
    return false;
  }
  return true;
}
<|endoftext|>


<commit_before>'use strict';

const BbPromise = require('bluebird');
const _ = require('lodash');
const Fse = require('fs-extra');
const Path = require('path');
const ChildProcess = require('child_process');
const zipper = require('zip-local');

BbPromise.promisifyAll(Fse);

class PkgPyFuncs {

  fetchConfig(){

    if (!this.serverless.service.custom){
      this.error("No serverless custom configurations are defined")
    }

    const config = this.serverless.service.custom.pkgPyFuncs

    if ( !config ) {
      this.error("No serverless-package-python-functions configuration detected. Please see documentation")
    }
    config.requirementsFile ? this.requirementsFile = config.requirementsFile  : this.requirementsFile = 'requirements.txt'
    config.buildDir ? this.buildDir = config.buildDir : this.error("No buildDir configuration specified")
    config.globalRequirements ? this.globalRequirements = config.globalRequirements : this.globalRequirements = null
    config.globalIncludes ? this.globalIncludes = config.globalIncludes : this.globalIncludes = null
    config.cleanup === undefined ? this.cleanup = true : this.cleanup = config.cleanup
    this.useDocker = config.useDocker || false
    this.dockerImage = config.dockerImage || `lambci/lambda:build-${this.serverless.service.provider.runtime}`
    this.containerName = config.containerName || 'serverless-package-python-functions'
  }

  clean(){
    if (!this.cleanup) {
      this.log('Cleanup is set to "false". Build directory and Docker container (if used) will be retained')
      return false
    }
    this.log("Cleaning build directory...")
    Fse.removeAsync(this.buildDir)
            .catch( err => { this.log(err) } )

    if (this.useDocker){
      this.log("Removing Docker container...")
      this.runProcess('docker', ['stop',this.containerName,'-t','0'])
    }
    return true
  }

  selectAll() {
    const functions = this.serverless.service.functions
    const info = _.map(functions, (target) => {
      return {
        name: target.name,
        includes: target.package.include
      }
    })
    return info
  }

  installRequirements(buildPath,requirementsPath){

    if ( !Fse.pathExistsSync(requirementsPath) ) {
      return
    }
    const size = Fse.statSync(requirementsPath).size

    if (size === 0){
      this.log(`WARNING: requirements file at ${requirementsPath} is empty. Skiping.`)
      return
    }

    let cmd = 'pip'
    let args = ['install','--upgrade','-t', buildPath, '-r', requirementsPath]
    if ( this.useDocker === true ){
      cmd = 'docker'
      args = ['exec',this.containerName, 'pip', ...args]
    }

    return this.runProcess(cmd,args)
  }

  checkDocker(){
    const out = this.runProcess('docker', ['version', '-f', 'Server Version {{.Server.Version}} & Client Version {{.Client.Version}}'])
    this.log(`Using Docker ${out}`)
  }

  runProcess(cmd,args){
    const ret = ChildProcess.spawnSync(cmd,args)
    if (ret.error){
      throw new this.serverless.classes.Error(`[serverless-package-python-functions] ${ret.error.message}`)
    }

    if (ret.stderr.length != 0){
      throw new this.serverless.classes.Error(`[serverless-package-python-functions] ${ret.stderr.toString()}`)
    }

    const out = ret.stdout.toString()
    return out
  }

  setupContainer(){
    let out = this.runProcess('docker',['ps', '-a', '--filter',`name=${this.containerName}`,'--format','{{.Names}}'])
    out = out.replace(/^\s+|\s+$/g, '')

    if ( out === this.containerName ){
      this.log('Container already exists. Reusing.')
    } else {
      this.runProcess(
        'docker',
        ['run', '--rm', '-dt', '-v', `${process.cwd()}:/var/task`,
          '--name',this.containerName, this.dockerImage, 'bash']
        )
      this.log('Container created')
    }
  }

  ensureImage(){
    const out = this.runProcess('docker', ['images', '--format','{{.Repository}}:{{.Tag}}','--filter',`reference=${this.dockerImage}`]).replace(/^\s+|\s+$/g, '')
    if ( out != this.dockerImage ){
      this.log(`Docker Image ${this.dockerImage} is not already installed on your system. Downloading. This might take a while. Subsequent deploys will be faster...`)
      this.runProcess('docker', ['pull', this.dockerImage])
    }
  }

  setupDocker(){
    if (!this.useDocker){
      return
    }
    this.log('Packaging using Docker container...')
    this.checkDocker()
    this.ensureImage()
    this.log(`Creating Docker container "${this.containerName}"...`)
    this.setupContainer()
    this.log('Docker setup completed')
  }

  makePackage(target){
    this.log(`Packaging ${target.name}...`)
    const buildPath = Path.join(this.buildDir, target.name)
    const requirementsPath = Path.join(buildPath,this.requirementsFile)
    // Create package directory and package files
    Fse.ensureDirSync(buildPath)
    // Copy includes
    let includes = target.includes
    if (this.globalIncludes){
      includes = _.concat(includes, this.globalIncludes)
    }
    _.forEach(includes, (item) => { Fse.copySync(item, buildPath) } )

    // Install requirements
    let requirements = [requirementsPath]
    if (this.globalRequirements){
      requirements = _.concat(requirements, this.globalRequirements)
    }
    _.forEach(requirements, (req) => { this.installRequirements(buildPath,req)})
    zipper.sync.zip(buildPath).compress().save(`${buildPath}.zip`)
  }

  constructor(serverless, options) {
    this.serverless = serverless;
    this.options = options;
    this.log = (msg) => { this.serverless.cli.log(`[serverless-package-python-functions] ${msg}`) }
    this.error = (msg) => { throw new Error(`[serverless-package-python-functions] ${msg}`) }
    this.hooks = {
      'before:package:createDeploymentArtifacts': () => BbPromise.bind(this)
        .then(this.fetchConfig)
        .then( () => { Fse.ensureDirAsync(this.buildDir) })
        .then(this.setupDocker)
        .then(this.selectAll)
        .map(this.makePackage),

      'after:deploy:deploy': () => BbPromise.bind(this)
        .then(this.clean)
    };

  }
}

module.exports = PkgPyFuncs;
<commit_msg>Set reasonable default for includes<commit_after>'use strict';

const BbPromise = require('bluebird');
const _ = require('lodash');
const Fse = require('fs-extra');
const Path = require('path');
const ChildProcess = require('child_process');
const zipper = require('zip-local');

BbPromise.promisifyAll(Fse);

class PkgPyFuncs {

  fetchConfig(){

    if (!this.serverless.service.custom){
      this.error("No serverless custom configurations are defined")
    }

    const config = this.serverless.service.custom.pkgPyFuncs

    if ( !config ) {
      this.error("No serverless-package-python-functions configuration detected. Please see documentation")
    }
    this.requirementsFile = config.requirementsFile || 'requirements.txt'
    config.buildDir ? this.buildDir = config.buildDir : this.error("No buildDir configuration specified")
    this.globalRequirements = config.globalRequirements || []
    this.globalIncludes = config.globalIncludes || []
    config.cleanup === undefined ? this.cleanup = true : this.cleanup = config.cleanup
    this.useDocker = config.useDocker || false
    this.dockerImage = config.dockerImage || `lambci/lambda:build-${this.serverless.service.provider.runtime}`
    this.containerName = config.containerName || 'serverless-package-python-functions'
  }

  clean(){
    if (!this.cleanup) {
      this.log('Cleanup is set to "false". Build directory and Docker container (if used) will be retained')
      return false
    }
    this.log("Cleaning build directory...")
    Fse.removeAsync(this.buildDir)
            .catch( err => { this.log(err) } )

    if (this.useDocker){
      this.log("Removing Docker container...")
      this.runProcess('docker', ['stop',this.containerName,'-t','0'])
    }
    return true
  }

  selectAll() {
    const functions = this.serverless.service.functions
    const info = _.map(functions, (target) => {
      return {
        name: target.name,
        includes: target.package.include
      }
    })
    return info
  }

  installRequirements(buildPath,requirementsPath){

    if ( !Fse.pathExistsSync(requirementsPath) ) {
      return
    }
    const size = Fse.statSync(requirementsPath).size

    if (size === 0){
      this.log(`WARNING: requirements file at ${requirementsPath} is empty. Skiping.`)
      return
    }

    let cmd = 'pip'
    let args = ['install','--upgrade','-t', buildPath, '-r', requirementsPath]
    if ( this.useDocker === true ){
      cmd = 'docker'
      args = ['exec',this.containerName, 'pip', ...args]
    }

    return this.runProcess(cmd,args)
  }

  checkDocker(){
    const out = this.runProcess('docker', ['version', '-f', 'Server Version {{.Server.Version}} & Client Version {{.Client.Version}}'])
    this.log(`Using Docker ${out}`)
  }

  runProcess(cmd,args){
    const ret = ChildProcess.spawnSync(cmd,args)
    if (ret.error){
      throw new this.serverless.classes.Error(`[serverless-package-python-functions] ${ret.error.message}`)
    }

    if (ret.stderr.length != 0){
      throw new this.serverless.classes.Error(`[serverless-package-python-functions] ${ret.stderr.toString()}`)
    }

    const out = ret.stdout.toString()
    return out
  }

  setupContainer(){
    let out = this.runProcess('docker',['ps', '-a', '--filter',`name=${this.containerName}`,'--format','{{.Names}}'])
    out = out.replace(/^\s+|\s+$/g, '')

    if ( out === this.containerName ){
      this.log('Container already exists. Reusing.')
    } else {
      this.runProcess(
        'docker',
        ['run', '--rm', '-dt', '-v', `${process.cwd()}:/var/task`,
          '--name',this.containerName, this.dockerImage, 'bash']
        )
      this.log('Container created')
    }
  }

  ensureImage(){
    const out = this.runProcess('docker', ['images', '--format','{{.Repository}}:{{.Tag}}','--filter',`reference=${this.dockerImage}`]).replace(/^\s+|\s+$/g, '')
    if ( out != this.dockerImage ){
      this.log(`Docker Image ${this.dockerImage} is not already installed on your system. Downloading. This might take a while. Subsequent deploys will be faster...`)
      this.runProcess('docker', ['pull', this.dockerImage])
    }
  }

  setupDocker(){
    if (!this.useDocker){
      return
    }
    this.log('Packaging using Docker container...')
    this.checkDocker()
    this.ensureImage()
    this.log(`Creating Docker container "${this.containerName}"...`)
    this.setupContainer()
    this.log('Docker setup completed')
  }

  makePackage(target){
    this.log(`Packaging ${target.name}...`)
    const buildPath = Path.join(this.buildDir, target.name)
    const requirementsPath = Path.join(buildPath,this.requirementsFile)
    // Create package directory and package files
    Fse.ensureDirSync(buildPath)
    // Copy includes
    let includes = target.includes || []
    if (this.globalIncludes){
      includes = _.concat(includes, this.globalIncludes)
    }
    _.forEach(includes, (item) => { Fse.copySync(item, buildPath) } )

    // Install requirements
    let requirements = [requirementsPath]
    if (this.globalRequirements){
      requirements = _.concat(requirements, this.globalRequirements)
    }
    _.forEach(requirements, (req) => { this.installRequirements(buildPath,req)})
    zipper.sync.zip(buildPath).compress().save(`${buildPath}.zip`)
  }

  constructor(serverless, options) {
    this.serverless = serverless;
    this.options = options;
    this.log = (msg) => { this.serverless.cli.log(`[serverless-package-python-functions] ${msg}`) }
    this.error = (msg) => { throw new Error(`[serverless-package-python-functions] ${msg}`) }
    this.hooks = {
      'before:package:createDeploymentArtifacts': () => BbPromise.bind(this)
        .then(this.fetchConfig)
        .then( () => { Fse.ensureDirAsync(this.buildDir) })
        .then(this.setupDocker)
        .then(this.selectAll)
        .map(this.makePackage),

      'after:deploy:deploy': () => BbPromise.bind(this)
        .then(this.clean)
    };

  }
}

module.exports = PkgPyFuncs;
<|endoftext|>