<commit_before>// Load dependencies
var app = require('electron').app,
    protocol = require('electron').protocol,
    ejs = require('ejs'),
    mime = require('mime')
    fs = require('fs'),
    url = require('url')

// Private variables
var userOpts = {}

// Helper functions
var compileEjs = function(contentBuffer) {
    var contentString = contentBuffer.toString(),
        compiledEjs = ejs.render(contentString, userOpts)

    return new Buffer(compiledEjs)
}

var protocolListener = function(request, callback) {
    try {
        var fileName = url.parse(request.url).pathname,
            fileContents = fs.readFileSync(fileName),
            extension = fileName.split('.').pop(),
            mimeType = mime.lookup(extension)

        if (extension === 'ejs') {
            userOpts.filename = fileName
            userOpts.ejse = this
            fileContents = compileEjs(fileContents)
            mimeType = 'text/html'
        }

        return callback({
            data: fileContents,
            mimeType: mimeType
        })

    } catch(exception) {
        return callback(-6) // NET_ERROR(FILE_NOT_FOUND, -6)
    }
}

// Module setup
var EJSE = function() {
    var self = this
    app.on('ready', function() {
        self.listen()
    })
}
EJSE.prototype = {

    // Start intercepting requests, looking for '.ejs' files.
    listen: function() {
        if (!protocol) return this
        protocol.interceptBufferProtocol('file', protocolListener.bind(this))
        return this
    },

    // Set the options to be passed in to `ejs.render()`.
    setOptions: function(optsIn) {
        userOpts = optsIn || {}
        return this
    },

    // Stop intercepting requests, restoring the original `file://` protocol handler.
    stopListening: function() {
        if (!protocol) return this

        protocol.uninterceptProtocol('file')
        return this
    }
}

// Expose stuff
module.exports = new EJSE()
<commit_msg>Fix handling of paths for Windows<commit_after>// Load dependencies
var app = require('electron').app,
    protocol = require('electron').protocol,
    ejs = require('ejs'),
    mime = require('mime'),
    fs = require('fs'),
    path = require('path'),
    url = require('url')

// Private variables
var userOpts = {}

// Helper functions
var compileEjs = function(contentBuffer) {
    var contentString = contentBuffer.toString(),
        compiledEjs = ejs.render(contentString, userOpts)

    return new Buffer(compiledEjs)
}

var protocolListener = function(request, callback) {
    try {
        var parsed = url.parse(request.url);
        var pathname = parsed.pathname;
        if (process.platform === 'win32' && !parsed.host.trim()) {
            pathname = pathname.substr(1);
        }

        var fileContents = fs.readFileSync(pathname),
            extension = pathname.split('.').pop(),
            mimeType = mime.lookup(extension)

        if (extension === 'ejs') {
            userOpts.filename = pathname
            userOpts.ejse = this
            fileContents = compileEjs(fileContents)
            mimeType = 'text/html'
        }

        return callback({
            data: fileContents,
            mimeType: mimeType
        })

    } catch(exception) {
        console.error(exception);
        return callback(-6) // NET_ERROR(FILE_NOT_FOUND, -6)
    }
}

// Module setup
var EJSE = function() {
    var self = this
    app.on('ready', function() {
        self.listen()
    })
}
EJSE.prototype = {

    // Start intercepting requests, looking for '.ejs' files.
    listen: function() {
        if (!protocol) return this
        protocol.interceptBufferProtocol('file', protocolListener.bind(this))
        return this
    },

    // Set the options to be passed in to `ejs.render()`.
    setOptions: function(optsIn) {
        userOpts = optsIn || {}
        return this
    },

    // Stop intercepting requests, restoring the original `file://` protocol handler.
    stopListening: function() {
        if (!protocol) return this

        protocol.uninterceptProtocol('file')
        return this
    }
}

// Expose stuff
module.exports = new EJSE()
<|endoftext|>


<commit_before>// Manage configurations

// Never use `location.hash` to store configurations.
// Evil guys may use that to obtain user private informations or execute authorized commands
//      by using hash configurations to inject remote modules and sending these urls to
//      the other users

// @return {Object}
function getAllConfigFromCookie() {
  // neuron=path=localhost
  // a=3; neuron=path=localhost
  var match = DOC.cookie.match(/(?:^|;)\s*neuron=([^;]*)/);
  return match ? parseQuery(match[1]) : {};
}

// 'path=localhost,ext=.min.js' earc
// -> { path: 'localhost', ext: '.min.js' }
// @param {!string} str The string of sh query
function parseQuery(str) {
  var obj = {};

  decodeURIComponent(str).split(',').forEach(function(key_value) {
    var pair = key_value.split('=');
    obj[pair[0]] = pair[1];
  });

  return obj;
}

// var neuron_loaded = [];
var NEURON_CONF = neuron.conf = {
  loaded: [],

  // transform ranges to specific version or fake version
  r: getRangeBaseVersion
};

// neuron#103
// ### without tree
// -> neuron use rough ranges
// If a module requires
// - `a@~1.2.3` -> `a@1.2`
// - `a@^1.2.3` -> `a@1`
// Then if `a@1.2.7` is defined, it will trigger `a@1.2` and `a@1`
function getRangeBaseVersion (range) {
  var parsed = parseSemver(range);
  var decorator = parsed.d;
  return decorator
    ? decorator === '~'
      // '~1.2.9' -> '1.2'
      ? parsed.a + '.' + parsed.b
      // '^1.2.9' -> '1'
      : parsed.a
    // '1.2.9' -> '1.2.9'
    : range
}

// ### with tree
// -> neuron uses the range map
// `a@1.2.3` -> `a@1.2.7`
// The structure of the tree is like:
// ```
// <name>: {
//   <version>: {
//     // dependencies and async dependencies
//     <dep-name>: [
//       {
//         <sync-dep-range>: <sync-dep-version>
//         ...
//       },
//       {
//         <async-dep-range>: <async-dep-version>
//         ...
//       }
//     ]
//   }
// }
// ...
// ```
function treeSetter (tree) {
  NEURON_CONF.r = getRangeVersion;
  return tree;
}

// @param {string=} dependentVersion the version of dependent in current context
// @param {string=} dependentName the name of dependent in current context
// @returns {string}
function getRangeVersion (range, name, dependentVersion, dependentName) {
  var tree = NEURON_CONF.tree;
  var dependent = dependentName
    // global package
    ? tree._
    : tree[dependentName] && tree[dependentName][dependentVersion];

  // if the range is defined in the tree
  return dependent && dependent[name] && dependent[name][range]
    // if not, fallback to fake version
    || getRangeBaseVersion(range);
}

// @return {false}
function returnFalse() {
  return false;
}

function justReturn(subject) {
  return subject;
}

// @const
// #81: We restricts protocol to 'http' and 'https',
//    because if it is possible for webviews to define their own protocol,
//    allowing to set `path` with custom protocol will be extremely dangerous
var REGEX_IS_LOCALHOST = /^(?:http|https)?\/\/localhost/;
var NORMAL_ATTRIBUTE = {
  S: justReturn,
  C: returnFalse
};

var CONF_ATTRIBUTES = {

  // The server where loader will fetch modules from
  // if use `'localhost'` as `base`, switch on debug mode
  'path': {
    // Setter function
    S: function(path) {
      // Make sure
      // - there's one and only one slash at the end
      // - `conf.path` is a directory
      return path.replace(/\/*$/, '/');
    },

    // Cookie checker
    C: function(path) {

      // For the sake of security,
      // we only support to set path to '%://localhost%' in cookie.
      // If there's a XSS bug in a single page,
      // attackers could use this cookie to redirect all javascript module to anything they want
      return REGEX_IS_LOCALHOST.test(path);
    }
  },

  // We don't allow this, just use facade configurations and manage it on your own
  // 'vars',
  // var: {
  // },

  'loaded': NORMAL_ATTRIBUTE,
  'tree': {
    S: treeSetter
  },
  'ext': {
    S: justReturn
  },
  'combo': NORMAL_ATTRIBUTE
};

var CONF_ATTRIBUTE_LIST = Object.keys(CONF_ATTRIBUTES);
var range_map = {};

// This transformer will be used if any range map is specified and configured.
function rangeMapping(range, name) {
  // '~1.2.3' -> '~1.2.0'
  var base = getBaseRange(range);
  var ranges = range_map[name] || {};

  // Two purpose:
  // - map: range -> version
  // - globally control and inject the specified version
  return ranges[base] ||

  // if `range` is a normal version, or not specified, remain the origin.
  range;
}

function cleanRanges(ranges) {
  var name;

  for (name in ranges) {
    cleanRangeMap(ranges[name]);
  }
}

function cleanRangeMap(map) {
  var range;
  var key;

  for (range in map) {
    // '1.2.3'  -> '1.2.3'
    // '~1.2.3' -> '~1.2.0'
    // 'latest' -> 'latest'
    key = getBaseRange(range);
    if (!(key in map)) {
      map[key] = map[range];
    }
  }
}

var cookie_conf = getAllConfigFromCookie();

// Santitize cookie configurations
CONF_ATTRIBUTE_LIST.forEach(function(key) {
  var cookie_checker;

  if (
    (key in cookie_conf)
    && (cookie_checker = CONF_ATTRIBUTES[key].C)
    && !cookie_checker(cookie_conf[key])
  ) {
      delete cookie_conf[key];
  }
});

function config(conf) {
  mix(conf, cookie_conf);

  CONF_ATTRIBUTE_LIST.forEach(function(key) {
    if ( key in conf ) {
      var result = CONF_ATTRIBUTES[key].S(conf[key]);

      if (result !== undefined) {
        NEURON_CONF[key] = result;
      }
    }
  });
}

// @expose
neuron.config = config;

<commit_msg>config: adds a method to generate base versions from each subversion of semver; #103<commit_after>// Manage configurations
//////////////////////////////////////////////////////////////////////

// 'path=localhost,ext=.min.js' earc
// -> { path: 'localhost', ext: '.min.js' }
// @param {!string} str The string of sh query
function parseQuery(str) {
  var obj = {};

  decodeURIComponent(str).split(',').forEach(function(key_value) {
    var pair = key_value.split('=');
    obj[pair[0]] = pair[1];
  });

  return obj;
}

// var neuron_loaded = [];
var NEURON_CONF = neuron.conf = {
  loaded: [],

  // transform ranges to specific version or fake version
  r: getRangeBaseVersion,
  v: function (version) {
    var parsed = parseSemver(version);
    return [
      getRangeBaseVersion(version, parsed, '~'),
      getRangeBaseVersion(version, parsed, '^')
    ];
  }
};

// neuron#103
// ### without tree
// -> neuron use rough ranges
// If a module requires
// - `a@~1.2.3` -> `a@1.2`
// - `a@^1.2.3` -> `a@1`
// Then if `a@1.2.7` is defined, it will trigger `a@1.2` and `a@1`
// @param {string} range
// @param {Object=} parsed
// @param {string=} decorator
function getRangeBaseVersion (range, parsed, decorator) {
  parsed || (parsed = parseSemver(range));
  decorator || (decorator = parsed.d);
  return decorator
    ? decorator === '~'
      // '~1.2.9' -> '1.2'
      ? parsed.a + '.' + parsed.b
      // '^1.2.9' -> '1'
      : parsed.a
    // '1.2.9' -> '1.2.9'
    : range
}

// ### with tree
// -> neuron uses the range map
// `a@1.2.3` -> `a@1.2.7`
// The structure of the tree is like:
// ```
// <name>: {
//   <version>: {
//     // dependencies and async dependencies
//     <dep-name>: [
//       {
//         <sync-dep-range>: <sync-dep-version>
//         ...
//       },
//       {
//         <async-dep-range>: <async-dep-version>
//         ...
//       }
//     ]
//   }
// }
// ...
// ```
function treeSetter (tree) {
  NEURON_CONF.r = getRangeVersion;

  // If tree is defined,
  NEURON_CONF.v = function () {
    return [];
  };
  return tree;
}

// @param {string=} dependentVersion the version of dependent in current context
// @param {string=} dependentName the name of dependent in current context
// @returns {string}
function getRangeVersion (range, name, dependentVersion, dependentName) {
  var tree = NEURON_CONF.tree;
  var dependent = dependentName
    // global package
    ? tree._
    : tree[dependentName] && tree[dependentName][dependentVersion];

  // if the range is defined in the tree
  return dependent && dependent[name] && dependent[name][range]
    // if not, fallback to fake version
    || getRangeBaseVersion(range);
}

// @return {false}
function returnFalse() {
  return false;
}

function justReturn(subject) {
  return subject;
}

// @const
// #81: We restricts protocol to 'http' and 'https',
//    because if it is possible for webviews to define their own protocol,
//    allowing to set `path` with custom protocol will be extremely dangerous
var REGEX_IS_LOCALHOST = /^(?:http|https)?\/\/localhost/;
var NORMAL_ATTRIBUTE = {
  S: justReturn,
  C: returnFalse
};

var CONF_ATTRIBUTES = {

  // The server where loader will fetch modules from
  // if use `'localhost'` as `base`, switch on debug mode
  'path': {
    // Setter function
    S: function(path) {
      // Make sure
      // - there's one and only one slash at the end
      // - `conf.path` is a directory
      return path.replace(/\/*$/, '/');
    },

    // Cookie checker
    C: function(path) {

      // For the sake of security,
      // we only support to set path to '%://localhost%' in cookie.
      // If there's a XSS bug in a single page,
      // attackers could use this cookie to redirect all javascript module to anything they want
      return REGEX_IS_LOCALHOST.test(path);
    }
  },

  // We don't allow this, just use facade configurations and manage it on your own
  // 'vars',
  // var: {
  // },

  'loaded': NORMAL_ATTRIBUTE,
  'tree': {
    S: treeSetter
  },
  'ext': {
    S: justReturn
  },
  'combo': NORMAL_ATTRIBUTE
};

var CONF_ATTRIBUTE_LIST = Object.keys(CONF_ATTRIBUTES);
var range_map = {};

// This transformer will be used if any range map is specified and configured.
function rangeMapping(range, name) {
  // '~1.2.3' -> '~1.2.0'
  var base = getBaseRange(range);
  var ranges = range_map[name] || {};

  // Two purpose:
  // - map: range -> version
  // - globally control and inject the specified version
  return ranges[base] ||

  // if `range` is a normal version, or not specified, remain the origin.
  range;
}

var cookie_conf = getAllConfigFromCookie();

// Santitize cookie configurations
CONF_ATTRIBUTE_LIST.forEach(function(key) {
  var cookie_checker;

  if (
    (key in cookie_conf)
    && (cookie_checker = CONF_ATTRIBUTES[key].C)
    && !cookie_checker(cookie_conf[key])
  ) {
      delete cookie_conf[key];
  }
});

function config(conf) {
  mix(conf, cookie_conf);

  CONF_ATTRIBUTE_LIST.forEach(function(key) {
    if ( key in conf ) {
      var result = CONF_ATTRIBUTES[key].S(conf[key]);

      if (result !== undefined) {
        NEURON_CONF[key] = result;
      }
    }
  });
}

// @expose
neuron.config = config;
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');

var db = MongoClient.connect("penn_db");
//get random from 1 to 100000
//return "num : {x,y}" from mongo

var num =  Math.floor(Math.random() * (100000 - 1001 + 1)) + 1001;
var url = 'mongodb://ec2-54-211-134-229.compute-1.amazonaws.com';

MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    console.log ("COnnection successful");
    var findDocuments = function(db, callback) {
	// Get the documents collection
	var collection = db.collection('bal1');
	collection.find({'_id': 1003}).toArray(function(err, docs) {
	    assert.equal(err, null);
	    console.log("Found the following records");
	    console.log(docs);
	    callback(docs);
	});
    }
    findDocuments(db,function(){
	db.close();
    });
});

app.get('/read', function (req, res) {
    res.send('Hello World');
})

//get random from 1 to 100000
//get value of x and y from mongo
//hash the values and update mongo
//return new values without a read to mongo
app.get('/update', function (req, res) {
    res.send('Hello World');
})

var server = app.listen(8081, function () {
    var host = server.address().address
    var port = server.address().port

    console.log("Example app listening at http://%s:%s", host, port)
})<commit_msg>removed {'_id': 1003} to test<commit_after>var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');

var db = MongoClient.connect("penn_db");
//get random from 1 to 100000
//return "num : {x,y}" from mongo

var num =  Math.floor(Math.random() * (100000 - 1001 + 1)) + 1001;
var url = 'mongodb://ec2-54-211-134-229.compute-1.amazonaws.com';

MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    console.log ("Connection successful");
    var findDocuments = function(db, callback) {
	// Get the documents collection
	var collection = db.collection('bal1');
	collection.find().toArray(function(err, docs) {
	    assert.equal(err, null);
	    console.log("Found the following records");
	    console.log(docs);
	    callback(docs);
	});
    }
    findDocuments(db,function(){
	db.close();
    });
});

app.get('/read', function (req, res) {
    res.send('Hello World');
})

//get random from 1 to 100000
//get value of x and y from mongo
//hash the values and update mongo
//return new values without a read to mongo
app.get('/update', function (req, res) {
    res.send('Hello World');
})

var server = app.listen(8081, function () {
    var host = server.address().address
    var port = server.address().port

    console.log("Example app listening at http://%s:%s", host, port)
})<|endoftext|>


<commit_before>/**
 *
 */
var fs=require('fs');
var http=require('http');

function printPage(req, res){
	res.writeHead(200, {
		'Content-Type': 'text/html'
	});

	fs.readFile('./html/index.html', function (err, data) {
		res.write(data);
		res.end();
	});
}

function printScript(req, res){
	res.writeHead(200, {
		'Content-Type': 'text/javascript'
	});

	fs.readFile('./html/script.js', function (err, data) {
		res.write(data);
		res.end();
	});
}

function printStylesheet(req, res){
	res.writeHead(200, {
		'Content-Type': 'text/css'
	});

	fs.readFile('./html/style.css', function (err, data) {
		res.write(data);
		res.end();
	});
}

function printRequest(req, res){
	res.writeHead(200, {
		'Content-Type': 'text/plain'
	});

	res.write(req.toString());
	res.end();

}

var server=http.createServer(function(req, res) {

	printRequest(req, res);

});

server.listen(8080);
<commit_msg>serve simple site<commit_after>/**
 *
 */
var fs=require('fs');
var http=require('http');

function printFile(file, res){

	fs.readFile('./html/'+file, function (err, data) {
		res.write(data);
		res.end();
	});
}

var server=http.createServer(function(req, res) {

	var file=req.url.split('/').pop();
	if(file.indexOf('.')>=0){

		fs.exists('./html/'+file, function(exists){

			if(exists){
				var contentTypes={
						js:'text/javascript',
						css:'text/css',
						html:'text/html',
							};

				var type=file.split('.').pop();
				res.writeHead(200, {
					'Content-Type': contentTypes[type]
				});
				printFile(file, res);

			}else{

				res.writeHead(404);
				res.end('File not found: '+file);

			}

		});
	}else{

		res.writeHead(500);
		res.end('resuest: '+file);

	}

});

server.listen(8080);
<|endoftext|>


<commit_before>var fs = require('fs-extra')
var _ = require('lodash-node/modern')

var defaultConfig = {

  // build options
  source: '.',
  destination: '_site',
  excludeFiles: [],
  includeFiles: [], // e.g. .htaccess

  // timezone
  timezone: 'America/Los_Angeles',

  // environment options
  env: 'production',

  // template options
  partialsDirectory: '_partials',
  layoutsDirectory: '_layouts',

  // plugin options
  pluginDirectory: '_plugins',
  excludePlugins: [],

  // post options
  postTypes: ['post'],
  excerptLength: 40,
  includeDrafts: false,

  // page options
  permalink: '/:title',

  // taxonomy options
  taxonomyTypes: [],

  // serve options
  port: 4000,
  watch: false,
  watchExcludes: []
}

// if no config file exists, just use an empty object
var userConfig = fs.existsSync('_config.json')
  ? fs.readJSONSync('_config.json')
  : {}

module.exports = Object.create(null, {

  init: {
    value: function(commandLineOptions) {

      _.assign(this, defaultConfig, userConfig, commandLineOptions)

      // make sure certain files are always excluded
      this.excludeFiles = _.union(
        this.excludeFiles,
        [
          '_*',
          '_*/**/*',
          'package.json',
          'node_modules/**/*'
        ]
      )

      // make sure certain directories are never watched
      this.watchExcludes = _.union(
        this.watchExcludes,
        ['node_modules', this.destination]
      )

      return this
    }
  }

})
<commit_msg>Add TODO to config as a reminder.<commit_after>var fs = require('fs-extra')
var _ = require('lodash-node/modern')

var defaultConfig = {

  // build options
  source: '.',
  destination: '_site',
  excludeFiles: [],
  includeFiles: [], // e.g. .htaccess

  // timezone
  timezone: 'America/Los_Angeles',

  // environment options
  env: 'production',

  // template options
  partialsDirectory: '_partials',
  layoutsDirectory: '_layouts',

  // plugin options
  pluginDirectory: '_plugins',
  excludePlugins: [],

  // post options
  postTypes: ['post'],
  excerptLength: 40,
  includeDrafts: false,

  // page options
  permalink: '/:title',

  // taxonomy options
  taxonomyTypes: [],

  // serve options
  port: 4000,
  watch: false,
  watchExcludes: []
}

// if no config file exists, just use an empty object
var userConfig = fs.existsSync('_config.json')
  ? fs.readJSONSync('_config.json')
  : {}

module.exports = Object.create(null, {

  // TODO: config needs to be reassignable for testing

  init: {
    value: function(commandLineOptions) {

      _.assign(this, defaultConfig, userConfig, commandLineOptions)

      // make sure certain files are always excluded
      this.excludeFiles = _.union(
        this.excludeFiles,
        [
          '_*',
          '_*/**/*',
          'package.json',
          'node_modules/**/*'
        ]
      )

      // make sure certain directories are never watched
      this.watchExcludes = _.union(
        this.watchExcludes,
        ['node_modules', this.destination]
      )

      return this
    }
  }

})
<|endoftext|>


<commit_before><commit_msg>Initial Ghost DOM<commit_after>/**
 * This file now provides the ability to manually include and initialize a
 * before and after hooks that are scoped to a unit test.
 *
 * Example usage:
 *
 *  var ghostdom = require('../test/ghost-dom');
 *
 *  describe(..., function () {
 *    ghostdom();
 *    ...
 *  }
 *
 */
var jsdom = require('jsdom').jsdom;

/**
 * Creates the jsdom elements if they do not exists.
 */
function createDom(markup) {

    var location;
    if (typeof markup === 'object') {
        location = markup.location;
        markup = markup.markup;
    }

    if (typeof global.document !== 'undefined') {
        return;
    }

    global.document = jsdom(markup || '');
    global.window = document.parentWindow;

    // HACK: Necessary so that you can include the jsdom before including
    // React. Otherwise React will attempt to check the userAgent and throw an
    // exception.
    //
    // TODO: Allow override the userAgent
    global.navigator = {
        userAgent: 'Ghost'
    };

    if (location) {
        global.location = location;
        global.window.location = location;
    }

}

/**
 * Cleans up the jsdom elements.
 */
function removeDom() {
    delete global.navigator;
    delete global.location;
    delete global.window;
    delete global.document;
}

/**
 * Adds before and after hooks to enable the creation and cleanup of jsdom
 * objects.
 *
 * @param {String} markup The markup it initialize jsdom with.
 */
function addScopedHooks(markup) {

    before(function () {
        createDom(markup);
    });

    after(function () {
        removeDom();
    });

}

module.exports = function (markup) {
    addScopedHooks(markup);
};
<|endoftext|>


<commit_before>var _ = require('underscore'),
    fs = require('fs'),
    path = require('path'),
    nconf = require('nconf');

var defaults = {
    development: {
        port: process.env['app_port'] || process.env['VCAP_APP_PORT'] || 3000,
        db: {
            read: true,
            write: true
        },
        log: {
            format: 'dev'
        }
    },
    test: {
        port: process.env['app_port'] || process.env['VCAP_APP_PORT']  || 3000,
        db: {
            read: true,
            write: true
        },
        log: {
            format: 'short'
        }
    },
    production: {
        port: process.env['app_port'] || process.env['VCAP_APP_PORT']  || 3000,
        db: {
            read: true,
            write: true
        },
        log: {
            format: 'default'
        }
    }
};

var environment = process.env['NODE_ENV'],
    configDir = path.join(__dirname + '/../config/'),
    environmentFile = configDir + environment + '.json',
    allFile = configDir + 'all.json';

var settings = {};

nconf.env().argv();

if (fs.existsSync(environmentFile)){
    nconf.file(environmentFile);
    settings = nconf.get('muxamp:db');
}
if (fs.existsSync(allFile)) {
    nconf.file(allFile);
    settings = _.extend({}, settings, nconf.get('muxamp:db'));
}

settings = _.extend({}, settings, (defaults[environment]['db'] || {}), nconf.get('muxamp:db'));

nconf.defaults({muxamp: defaults[environment]});
nconf.set('muxamp:db', settings);

switch (environment) {
    case 'development':
    case 'production':
    case 'test':
        break;
    default:
        console.log('WARNING:',
            'NODE_ENV does not match "development", "production", or "test".',
            'Configuration problems may occur.');
}

module.exports = nconf;<commit_msg>Finally fix the hacky configuration loading procedure.<commit_after>var _ = require('underscore'),
    fs = require('fs'),
    path = require('path'),
    nconf = require('nconf');

var defaults = {
    development: {
        port: process.env['app_port'] || process.env['VCAP_APP_PORT'] || 3000,
        db: {
            read: true,
            write: true
        },
        log: {
            format: 'dev'
        }
    },
    test: {
        port: process.env['app_port'] || process.env['VCAP_APP_PORT']  || 3000,
        db: {
            read: true,
            write: true
        },
        log: {
            format: 'short'
        }
    },
    production: {
        port: process.env['app_port'] || process.env['VCAP_APP_PORT']  || 3000,
        db: {
            read: true,
            write: true
        },
        log: {
            format: 'default'
        }
    }
};

nconf.env().argv();

var environment = nconf.get('NODE_ENV');
switch (environment) {
    case 'development':
    case 'production':
    case 'test':
        break;
    default:
        throw new Error('NODE_ENV does not match "development", "production", or "test"');
}

var configDir = path.join(__dirname + '/../config/'),
    environmentFile = configDir + environment + '.json',
    allFile = configDir + 'all.json',
    fileRead = false;

_([allFile, environmentFile]).each(function(file) {
    if (!fs.existsSync(file)) {
        return;
    }
    if (fileRead) {
        nconf.merge(JSON.parse(fs.readFileSync(file, 'utf8')));
    } else {
        nconf.add('file', {file: file});
        fileRead = true;
    }
});
nconf.defaults({muxamp: defaults[environment]});

module.exports = nconf;<|endoftext|>


<commit_before>const remote = require('electron').remote;
const fs = require('fs');

// Create window controls
(function() {
	document.getElementById('min-btn').addEventListener('click', () => {
		remote.getCurrentWindow().minimize();
	}, false);

	document.getElementById('max-btn').addEventListener('click', () => {
		if (!remote.getCurrentWindow().isMaximized()) {
			remote.getCurrentWindow().maximize();
		} else {
			remote.getCurrentWindow().unmaximize();
		}
	}, false);

	document.getElementById('close-btn').addEventListener('click', () => {
		remote.getCurrentWindow().close();
	}, false);
})();

// Create directory browse
const browseDir = function() {
	document.getElementById('browse-files').addEventListener('click', () => {
		let filePaths = remote.dialog.showOpenDialog({
			properties: ['openDirectory']
		});
		for (let filePath of filePaths) {
			console.log(filePath);
		}
	});
}

browseDir();

// Has the user chosen a asset directory?
//if () {
	// Display feed
//} else {
	// User browses for directory
//}<commit_msg>Managed to read all files in the main directory.<commit_after>const remote = require('electron').remote;
const fs = require('fs'),
	  path = require('path');

// Create window controls
(function() {
	document.getElementById('min-btn').addEventListener('click', () => {
		remote.getCurrentWindow().minimize();
	}, false);

	document.getElementById('max-btn').addEventListener('click', () => {
		if (!remote.getCurrentWindow().isMaximized()) {
			remote.getCurrentWindow().maximize();
		} else {
			remote.getCurrentWindow().unmaximize();
		}
	}, false);

	document.getElementById('close-btn').addEventListener('click', () => {
		remote.getCurrentWindow().close();
	}, false);
})();

// Create directory browse
const browseDir = function() {
	document.getElementById('browse-files').addEventListener('click', () => {
		var filePaths = remote.dialog.showOpenDialog({
			properties: ['openDirectory']
		});
		for (var filePath of filePaths) {
			console.log(filePath);
		}

		walk(filePath, function(curPath, stat) {
			console.log(curPath);
		});
	});
}

browseDir();

function walk(currentDirPath, callback) {
	fs.readdir(currentDirPath, (err, files) => {
		files.forEach(file => {
			var curPath = path.join(currentDirPath, file);
			var stat = fs.statSync(curPath);
			if (stat.isFile()) {
				callback(curPath, stat);
			} else if (stat.isDirectory()) {
				walk(curPath, callback);
			}
		})
	});
}

// Has the user chosen a asset directory?
//if () {
	// Display feed
//} else {
	// User browses for directory
	// Create directory browse
/*	const browseDir = function() {
		document.getElementById('browse-files').addEventListener('click', () => {
			let filePaths = remote.dialog.showOpenDialog({
				properties: ['openDirectory']
			});
			for (let filePath of filePaths) {
				console.log(filePath);
			}
		});
	}

	browseDir();*/
//}<|endoftext|>


<commit_before>'use strict';

var Promise = require('promise');
var fs = require('fs-promise');
var path = require('path');
var request = require('request-promise');
var cheerio = require('cheerio');
var Table = require('easy-table');

var projects = path.join(__dirname, 'projects.json');

getProjectURLs(projects).then(
  requestAll).then(
  getVotes).then(
  createTable).then(
  print).catch(
  console.error.bind(console));

function getProjectURLs(file) {
  return fs.readFile(file).then(
    JSON.parse);
}

function requestAll(urls) {
  return Promise.all(urls.map(request));
}

function getVotes(htmls) {
  return htmls.map(parseBody);
}

function parseBody(html) {
  var $ = cheerio.load(html);
  return  [
    $('h1#page-title').text().trim(),
    $('.pane-node-flag-vote-1-count div').text().trim()
  ];
}

function createTable(rows) {
  var table = new Table();
  rows.forEach(function(project) {
    table.cell('Projekt', project[0]);
    table.cell('Głosy', project[1]);
    table.newRow();
  });
  table.sort(['Głosy|des']);
  return table;
}

function print(table) {
  console.log(table.toString());
}
<commit_msg>better sort<commit_after>'use strict';

var Promise = require('promise');
var fs = require('fs-promise');
var path = require('path');
var request = require('request-promise');
var cheerio = require('cheerio');
var Table = require('easy-table');

var projects = path.join(__dirname, 'projects.json');

getProjectURLs(projects).then(
  requestAll).then(
  getVotes).then(
  createTable).then(
  print).catch(
  console.error.bind(console));

function getProjectURLs(file) {
  return fs.readFile(file).then(
    JSON.parse);
}

function requestAll(urls) {
  return Promise.all(urls.map(request));
}

function getVotes(htmls) {
  return htmls.map(parseBody);
}

function parseBody(html) {
  var $ = cheerio.load(html);
  return  [
    $('h1#page-title').text().trim(),
    $('.pane-node-flag-vote-1-count div').text().trim()
  ];
}

function createTable(rows) {
  rows.sort(function(a, b) {
    return toNum(b[1]) - toNum(a[1]);
  });

  var table = new Table();
  rows.forEach(function(project, i) {
    table.cell('Lp.', i + 1);
    table.cell('Projekt', project[0], shortStr);
    table.cell('Głosy', toNum(project[1]), Table.Number(0));
    table.newRow();
  });
  return table;
}

function shortStr(str) {
  if (str.length > 50) {
    return str.slice(0, 49) + '…';
  } else {
    return str;
  }
}

function toNum(str) {
  var val = parseInt(str);
  return isNaN(val) ? 0 : val;
}

function print(table) {
  console.log(table.toString());
}
<|endoftext|>


<commit_before>'use strict';

var Componser = require('./componser')
  , Parser = require('./parser')
  , path = require('path')
  , fs = require('fs');

//
// Empty function
//
function noop(){}

function Configuration() {
  if (!(this instanceof Configuration)) return new Configuration();

  // Required for parsing and composing the configurations.
  this.data = Object.create(null);
  this.source = '';

  // The actual parsers and configurators.
  this.componser = new Componser(this);
  this.parser = new Parser(this);
  this.definitions = Configuration;
}

Configuration.prototype.__proto__ = require('events').EventEmitter.prototype;

/**
 * Read out a configuration file and parse it for conversion.
 *
 * @param {String} location The path to the configuration file.
 * @param {Function} fn Callback
 * @returns {Configuration}
 */
Configuration.prototype.read = function read(location, fn) {
  var type = path.extname(location).substr(1)
    , self = this;

  fn = fn || noop;

  if (!(type in this.parser)) {
    fn.call(this, new Error('Invalid file, no parser for this extension'));
    return this;
  }

  fs.readFile(location, 'utf-8', function read(err, source) {
    if (err) return fn(err);

    //
    // Set the `source` and emit the `read` event with file extension so it can
    // start with parsing the original file's source. After everything is parsed
    // we can call the supplied callback which can process things further.
    //
    self.source = source;
    self.emit('read', type);

    fn(err, source);
  });

  return this;
};

/**
 * Config sections and bitmasks.
 *
 * @type {Object}
 * @api private
 */
Configuration.masks = {
    global:   1 << 1  // 2
  , defaults: 1 << 2  // 4
  , frontend: 1 << 3  // 8
  , listen:   1 << 4  // 16
  , backend:  1 << 5  // 32
};

/**
 * Configuration keys and bitwise value, each bitwise value appoints
 * sections to which the key belongs.
 *
 * @type {Object}
 * @api private
 */
Configuration.keys = {
    2: [
        'ca-base', 'chroot', 'crt-base', 'daemon', 'debug', 'gid', 'group'
      , 'log-send-hostname', 'maxcompcpuusage', 'maxcomprate', 'maxconnrate'
      , 'maxpipes', 'maxsslconn', 'nbproc', 'node', 'noepoll', 'nokqueue'
      , 'nopoll', 'nosplice', 'pidfile', 'quiet', 'spread-checks', 'stats'
      , 'tune.bufsize', 'tune.chksize', 'tune.comp.maxlevel', 'tune.http.cookielen'
      , 'tune.http.maxhdr', 'tune.maxaccept', 'tune.maxpollevents'
      , 'tune.maxrewrite', 'tune.pipesize', 'tune.rcvbuf.client'
      , 'tune.rcvbuf.server', 'tune.sndbuf.client', 'tune.sndbuf.server'
      , 'tune.ssl.cachesize', 'tune.ssl.lifetime', 'tune.ssl.maxrecord'
      , 'tune.zlib.memlevel', 'tune.zlib.windowsize', 'uid', 'ulimit-n'
      , 'unix-bind', 'user'
    ]
  , 24: [
        'bind', 'capture cookie', 'capture request header', 'capture response header'
      , 'monitor fail', 'tcp-request connection', 'use_backend'
    ]
  , 28: [
        'backlog', 'default_backend', 'monitor-net', 'monitor-uri'
      , 'option accept-invalid-http-request', 'option clitcpka', 'option contstats'
      , 'option dontlog-normal', 'option dontlognull', 'option http-use-proxy-header'
      , 'option log-separate-errors', 'option logasap', 'option socket-stats'
      , 'option tcp-smart-accept', 'rate-limit sessions', 'timeout client'
      , 'unique-id-format', 'unique-id-header'
    ]
  , 30: [ 'maxconn' ]
  , 48: [
        'appsession', 'dispatch', 'http-check expect', 'server', 'stats admin'
      , 'stats http-request', 'stick match', 'stick on', 'stick store-request'
      , 'stick store-response', 'stick-table', 'tcp-response content'
      , 'tcp-response inspect-delay', 'use-server'
    ]
  , 52: [
        'balance', 'cookie', 'default-server', 'fullconn', 'hash-type'
      , 'http-check disable-on-404', 'http-check send-state', 'option abortonclose'
      , 'option accept-invalid-http-response', 'option allbackups'
      , 'option checkcache', 'option httpchk', 'option lb-agent-chk'
      , 'option ldap-check', 'option log-health-checks', 'option mysql-check'
      , 'option persist', 'option pgsql-check', 'option redis-check'
      , 'option redispatch', 'option smtpchk', 'option srvtcpka'
      , 'option ssl-hello-chk', 'option tcp-smart-connect', 'option transparent'
      , 'persist rdp-cookie', 'retries', 'source', 'stats auth', 'stats enable'
      , 'stats hide-version', 'stats realm', 'stats refresh', 'stats scope'
      , 'stats show-desc', 'stats show-legends', 'stats show-node', 'stats uri'
      , 'timeout check', 'timeout connect', 'timeout queue', 'timeout server'
      , 'timeout tunnel'
    ]
  , 56: [
        'acl', 'block', 'force-persist', 'http-request', 'id', 'ignore-persist'
      , 'redirect', 'reqadd', 'reqallow', 'reqdel', 'reqdeny', 'reqiallow'
      , 'reqidel', 'reqideny', 'reqipass', 'reqirep', 'reqisetbe', 'reqitarpit'
      , 'reqpass', 'reqrep', 'reqsetbe', 'reqtarpit', 'rspadd', 'rspdel'
      , 'rspdeny', 'rspidel', 'rspideny', 'rspirep', 'rsprep', 'tcp-request content'
      , 'tcp-request inspect-delay'
    ]
  , 58: [ 'description' ]
  , 60: [
        'bind-process', 'compression', 'disabled', 'enabled', 'errorfile', 'errorloc'
      , 'errorloc302', 'errorloc303', 'grace', 'mode', 'option forceclose'
      , 'option forwardfor', 'option http-no-delay', 'option http-pretend-keepalive'
      , 'option http-server-close', 'option http_proxy', 'option httpclose'
      , 'option httplog', 'option independent-streams', 'option nolinger'
      , 'option originalto', 'option splice-auto', 'option splice-request'
      , 'option splice-response', 'option tcpka', 'option tcplog'
      , 'timeout http-keep-alive', 'timeout http-request', 'timeout tarpit'
    ]
  , 62: [ 'log' ]
};

Configuration.sections = Object.keys(Configuration.sections);

Configuration.allowed = Object.create(null);

//
// Generate allowed config keys per section from the bitmasks.
//
Configuration.sections.forEach(function prepareKeys(section) {
  var mask = Configuration.masks.sections[section]
    , current;

  Object.keys(Configuration.keys).forEach(function bitmask(bit) {
    current = Configuration.allowed[section] || [];
    if (mask & +bit) Configuration.allowed[section] = current.concat(Configuration.keys[bit]);
  });
});

//
// Expose the Config
//
module.exports = Configuration;
<commit_msg>[api] Configuration class progress<commit_after>'use strict';

var Orchestrator = require('./orchestrator')
  , Componser = require('./componser')
  , Parser = require('./parser')
  , path = require('path')
  , fs = require('fs');

//
// Empty function
//
function noop(){}

function Configuration() {
  if (!(this instanceof Configuration)) return new Configuration();

  // Required for parsing and composing the configurations.
  this.data = Object.create(null);
  this.source = '';

  // The actual parsers and configurators.
  this.componser = new Componser(this);
  this.parser = new Parser(this);
  this.definitions = Configuration;
}

Configuration.prototype.__proto__ = require('events').EventEmitter.prototype;

/**
 * Read out a configuration file and parse it for conversion.
 *
 * @param {String} location The path to the configuration file.
 * @param {Function} fn Callback
 * @returns {Configuration}
 */
Configuration.prototype.read = function read(location, fn) {
  var type = path.extname(location).substr(1)
    , self = this;

  fn = fn || noop;

  if (!(type in this.parser)) {
    fn.call(this, new Error('Invalid file, no parser for this extension'));
    return this;
  }

  fs.readFile(location, 'utf-8', function read(err, source) {
    if (err) return fn(err);

    //
    // Set the `source` and emit the `read` event with file extension so it can
    // start with parsing the original file's source. After everything is parsed
    // we can call the supplied callback which can process things further.
    //
    self.source = source;
    self.emit('read', type);

    fn(err, source);
  });

  return this;
};

/**
 * Write the config to file, composer type is aquired from file extension.
 *
 * @param {String} location file location
 * @param {Function} fn
 * @api public
 */
Configuration.prototype.write = function write(location, fn) {
  var type = path.extname(location).substr(1);

  //
  // Check if the given extension is supported by our configuration generator.
  // Default to cfg as that's the format that HAProxy supports.
  //
  if (!(type in this.composer)) type = 'cfg';

  fs.writeFile(location, this.composer[type](), fn);
  return this;
};

/**
 * Verify the current config by using HAProxies check.
 *
 * @param {Function} fn
 * @api public
 */
Configuration.prototype.verify = function verify(fn) {
  var tmp = '/tmp/haproxy.'+ Math.random().toString(36).substring(2).toUpperCase()
    , orchestrator = new Orchestrator({ config: tmp })
    , data = this.componser.cfg();

  fs.writeFile(tmp, data, function hollaback(err) {
    if (err) return fn(err);

    orchestrator.verify(function verification() {
      fn.apply(exports, arguments);

      //
      // We don't care if it fails or not, each file would have a unique name.
      // And we don't really need to remove it from the file system but it's
      // just `nice` do some additional cleanup
      //
      fs.unlink(tmp, function likeigiveafuck() {});
    });
  });

  return this;
};

/**
 * Get value of the section-key combination.
 *
 * @param {String} section predefined section
 * @param {String} key
 * @return {String} key value
 * @api private
 */
Configuration.prototype.get = function get(section, name, key) {
  return this.data[section][name][key];
};

/**
 * Set the section-key combination to value.
 *
 * @param {String} section predefined section
 * @param {String} key
 * @param {String} value
 * @return {Object} bind comment to key.
 * @api private
 */
Configuration.prototype.set = function set(section, name, key, value) {
  var element, sub;

  // Check if the current key is allowed to be set on the section.
  if (!~keys[section].indexOf(key)) return;

  this.data[section] = element = this.data[section] || Object.create(null);
  element[name] = sub = element[name] || Object.create(null);
  sub[key] = value;

  // Expose comment function bound to key.
  return this.comment.bind(this, section, name, key);
};

/**
 * Adds content to key, transforms value to array if required
 *
 * @param {String} section predefined section
 * @param {String} key
 * @param {String} value
 * @return {Object} bind comment to key.
 * @api private
 */
Configuration.prototype.add = function add(section, name, key, value) {
  var element, sub;

  // Check if the current key is allowed to be set on the section.
  if (!~keys[section].indexOf(key)) return;

  this.data[section] = element = this.data[section] || Object.create(null);
  element[name] = sub = element[name] || Object.create(null);

  // If this key is undefined just call set.
  if (!sub[key]) return this.set(section, name, key, value);

  // Convert to array so we can just push to it.
  if (sub[key] && typeof sub[key] === 'string') sub[key] = [sub[key]];

  // Add the value
  sub[key].push(value);

  // Expose comment function bound to key.
  return this.comment.bind(this, section, key);
};

/**
 * Add comment to section-key combinations. General section comments are added
 * to `commentary.pre`. Return early if there is no actual text.
 *
 * @param {String} section predefined section
 * @param {String} key
 * @param {String} text
 * @return {String} text
 * @api private
 */
Configuration.prototype.comment = function comment(section, name, key, text) {
  var element, sub;

  // Do add comments, will you!
  if (!text) return;

  this.data[section] = element = this.data[section] || Object.create(null);
  element[name] = sub = element[name] || Object.create(null);
  sub.commentary = sub.commentary || Object.create(null);

  return sub.commentary[key] = text.trim();
};

/**
 * Reset and clear the current config
 *
 * @api public
 */
Configuration.prototype.reset = function reset() {
  this.data = Object.create(null);
  this.source = '';

  return this;
};

/**
 * Config sections and bitmasks.
 *
 * @type {Object}
 * @api private
 */
Configuration.masks = {
    global:   1 << 1  // 2
  , defaults: 1 << 2  // 4
  , frontend: 1 << 3  // 8
  , listen:   1 << 4  // 16
  , backend:  1 << 5  // 32
};

/**
 * Configuration keys and bitwise value, each bitwise value appoints
 * sections to which the key belongs.
 *
 * @type {Object}
 * @api private
 */
Configuration.keys = {
    2: [
        'ca-base', 'chroot', 'crt-base', 'daemon', 'debug', 'gid', 'group'
      , 'log-send-hostname', 'maxcompcpuusage', 'maxcomprate', 'maxconnrate'
      , 'maxpipes', 'maxsslconn', 'nbproc', 'node', 'noepoll', 'nokqueue'
      , 'nopoll', 'nosplice', 'pidfile', 'quiet', 'spread-checks', 'stats'
      , 'tune.bufsize', 'tune.chksize', 'tune.comp.maxlevel', 'tune.http.cookielen'
      , 'tune.http.maxhdr', 'tune.maxaccept', 'tune.maxpollevents'
      , 'tune.maxrewrite', 'tune.pipesize', 'tune.rcvbuf.client'
      , 'tune.rcvbuf.server', 'tune.sndbuf.client', 'tune.sndbuf.server'
      , 'tune.ssl.cachesize', 'tune.ssl.lifetime', 'tune.ssl.maxrecord'
      , 'tune.zlib.memlevel', 'tune.zlib.windowsize', 'uid', 'ulimit-n'
      , 'unix-bind', 'user'
    ]
  , 24: [
        'bind', 'capture cookie', 'capture request header', 'capture response header'
      , 'monitor fail', 'tcp-request connection', 'use_backend'
    ]
  , 28: [
        'backlog', 'default_backend', 'monitor-net', 'monitor-uri'
      , 'option accept-invalid-http-request', 'option clitcpka', 'option contstats'
      , 'option dontlog-normal', 'option dontlognull', 'option http-use-proxy-header'
      , 'option log-separate-errors', 'option logasap', 'option socket-stats'
      , 'option tcp-smart-accept', 'rate-limit sessions', 'timeout client'
      , 'unique-id-format', 'unique-id-header'
    ]
  , 30: [ 'maxconn' ]
  , 48: [
        'appsession', 'dispatch', 'http-check expect', 'server', 'stats admin'
      , 'stats http-request', 'stick match', 'stick on', 'stick store-request'
      , 'stick store-response', 'stick-table', 'tcp-response content'
      , 'tcp-response inspect-delay', 'use-server'
    ]
  , 52: [
        'balance', 'cookie', 'default-server', 'fullconn', 'hash-type'
      , 'http-check disable-on-404', 'http-check send-state', 'option abortonclose'
      , 'option accept-invalid-http-response', 'option allbackups'
      , 'option checkcache', 'option httpchk', 'option lb-agent-chk'
      , 'option ldap-check', 'option log-health-checks', 'option mysql-check'
      , 'option persist', 'option pgsql-check', 'option redis-check'
      , 'option redispatch', 'option smtpchk', 'option srvtcpka'
      , 'option ssl-hello-chk', 'option tcp-smart-connect', 'option transparent'
      , 'persist rdp-cookie', 'retries', 'source', 'stats auth', 'stats enable'
      , 'stats hide-version', 'stats realm', 'stats refresh', 'stats scope'
      , 'stats show-desc', 'stats show-legends', 'stats show-node', 'stats uri'
      , 'timeout check', 'timeout connect', 'timeout queue', 'timeout server'
      , 'timeout tunnel'
    ]
  , 56: [
        'acl', 'block', 'force-persist', 'http-request', 'id', 'ignore-persist'
      , 'redirect', 'reqadd', 'reqallow', 'reqdel', 'reqdeny', 'reqiallow'
      , 'reqidel', 'reqideny', 'reqipass', 'reqirep', 'reqisetbe', 'reqitarpit'
      , 'reqpass', 'reqrep', 'reqsetbe', 'reqtarpit', 'rspadd', 'rspdel'
      , 'rspdeny', 'rspidel', 'rspideny', 'rspirep', 'rsprep', 'tcp-request content'
      , 'tcp-request inspect-delay'
    ]
  , 58: [ 'description' ]
  , 60: [
        'bind-process', 'compression', 'disabled', 'enabled', 'errorfile', 'errorloc'
      , 'errorloc302', 'errorloc303', 'grace', 'mode', 'option forceclose'
      , 'option forwardfor', 'option http-no-delay', 'option http-pretend-keepalive'
      , 'option http-server-close', 'option http_proxy', 'option httpclose'
      , 'option httplog', 'option independent-streams', 'option nolinger'
      , 'option originalto', 'option splice-auto', 'option splice-request'
      , 'option splice-response', 'option tcpka', 'option tcplog'
      , 'timeout http-keep-alive', 'timeout http-request', 'timeout tarpit'
    ]
  , 62: [ 'log' ]
};

/**
 * Change config strings to suitable function names.
 *
 * @param {String} value function name
 * @return {String}
 * @api private
 */
Configuration.functionalize = function functionalize(value) {
  return value.toLowerCase().replace(/[^a-z]/g, '');
};

//
// Array of possible configuration sections.
//
Configuration.sections = Object.keys(Configuration.sections);

//
// An object with the allowed sections & configuration value mapping.
//
Configuration.allowed = Object.create(null);

//
// Generate allowed config keys per section from the bitmasks.
//
Configuration.sections.forEach(function prepareKeys(section) {
  var mask = Configuration.masks.sections[section]
    , current;

  Object.keys(Configuration.keys).forEach(function bitmask(bit) {
    current = Configuration.allowed[section] || [];
    if (mask & +bit) Configuration.allowed[section] = current.concat(Configuration.keys[bit]);
  });
});

//
// Generate some helper methods on each section to quickly set and get values.
//
Configuration.sections.forEach(function prepareFunctions(section) {
  if (section in Configuration.prototype) throw new Error('Duplicate method '+ section);

  Configuration.prototype[section] = function setup(name) {
    // Defaults have no name parameter, but for eaz and consistency we
    // are gonna pretend it has a general name section.
    if (!name || section === 'defaults') name = 'general';

    // Add getters and setters to each section.
    var result = Object.create(null);
    result.__proto__ = {
      get: this.get.bind(this, section, name),
      set: this.set.bind(this, section, name),
      add: this.add.bind(this, section, name),
      comment: this.comment.bind(this, section, name, 'pre'),
      and: this
    };

    // Also add camelCased proxies for each key in the section.
    keys[section].forEach(function addProxies(key) {
      result.__proto__[Configuration.functionalize(key)] = this.set.bind(this, section, name, key);
    }, this);

    return result;
  };
});

//
// Expose the Config
//
module.exports = Configuration;
<|endoftext|>


<commit_before>/**
 * Created by dungtran on 8/20/17.
 */

import PasswordStrengthChecker from './components/PasswordStrengthChecker';
export PasswordStrengthChecker;<commit_msg>export component<commit_after>/**
 * Created by dungtran on 8/20/17.
 */

import PasswordStrengthChecker from './components/PasswordStrengthChecker';
export default PasswordStrengthChecker;<|endoftext|>


<commit_before>'use strict';

var util = require("util");
var mongoose = require('mongoose');
var path = process.cwd();
require('dotenv').load();
var app = require('express')();

if (process.env.MONGOLAB_URI) {
    mongoose.connect(process.env.MONGOLAB_URI);
} else {
    mongoose.connect(process.env.MONGO_URI);
}

var BanyaUsers = require('./app/models/banyaUsers.js');
var checkUser = require("./app/models/checkUser.js");

var start = require("./app/controllers/commands/start.js");
var help = require("./app/controllers/commands/help.js");
var motivateme = require("./app/controllers/commands/motivateme.js");
var trollme = require("./app/controllers/commands/trollme.js");
var trolluser = require("./app/controllers/commands/trolluser.js");
var requestfeature = require("./app/controllers/commands/requestfeature.js");
var reportbug = require("./app/controllers/commands/reportbug.js");

var TeaBot = require("teabot")(process.env.BOT_TOKEN, process.env.BOT_NAME);
TeaBot.use('analytics', require('teabot-botan')(process.env.BOTAN_TOKEN));

function printFrom(dialog) {
    var from = {
        id: dialog.message.from.id,
        username: dialog.message.from.username,
        first_name: dialog.message.from.first_name,
        last_name: dialog.message.from.last_name
    };
    var command = dialog.message.command;
    console.log(new Date().toISOString(), "command " + command + " request from: ", from.id, from.username, from.first_name, from.last_name);
}

function getName(dialog) {
    return dialog.message.from.first_name || dialog.message.from.username;
}

function getCurrentUsers(next) {
    BanyaUsers.find({}, function(err, users) {
        if (err) console.error(err);
        next(users);
    });
}

function userExists(name, next) {
    BanyaUsers.findOne({ $or: [ { 'user.secondName': name }, { 'user.firstName': name } ]}, function(err, user) {
        if (err) console.error(err);
        if (user) {
            console.log("--- found this user: ", user.userid, user.user.username, user.user.firstName, user.user.secondName);
        }
        if (next) { next(user); } else return user;
    });
}

function prepareTempData(data, user) {
    data.userid = user.userid;
    data.user = {
        firstName: user.user.firstName,
        secondName: user.user.secondName
    };
    return data;
}

TeaBot.onError(function (e) {
    console.error('TeaBot error:', e.stack);
});

// COMMANDS //

TeaBot
    .defineCommand('/start', function (dialog) {
        // console.log(util.inspect(dialog.message.from));
        printFrom(dialog);
        checkUser(dialog.message, function(user) {
            dialog
                .setKeyboard()
                .sendMessage(start(getName(dialog)));
        });

    })

    .defineCommand('/help', function (dialog) {
        printFrom(dialog);
        dialog
          .setKeyboard()
          .sendMessage(help(getName(dialog)));
    })

    .defineCommand('/motivateme', function (dialog) {
        printFrom(dialog);
        dialog
          .setKeyboard()
          .sendMessage(motivateme());
    })

    .defineCommand('/trollme', function (dialog) {
        printFrom(dialog);
        dialog.setKeyboard();
        trollme(dialog.message, function(response) {
            dialog.sendMessage(response);
        });
    })

    .defineCommand('/trolluser', function(dialog) {
        printFrom(dialog);
        dialog.startAction('/trolluser');
        getCurrentUsers(function(users) {
            var keyboard = [];
            users.forEach((el) => {
                if (el.userid != 170522191) {
                    keyboard.push(new Array((el.user.secondName) ? el.user.firstName + " " + el.user.secondName : el.user.firstName));
                }
            });
            keyboard.push(['другого']);
            keyboard.push(['/cancel']);

            dialog.setKeyboard(keyboard, true, true);
            dialog.sendMessage("Кого ты хочешь потроллить (скролл работает, если что)?");
        });

    })

    .defineCommand('/requestfeature', function (dialog) {
        printFrom(dialog);
        dialog.startAction('/requestfeature').sendMessage("Опиши предлагаемую фичу. Только коротко.");
    })

    .defineCommand('/reportbug', function (dialog) {
        printFrom(dialog);
        dialog.startAction('/reportbug').sendMessage("Опиши найденную ошибку. Только коротко.");
    })

    .defineCommand('/cancel', function (dialog) {
        printFrom(dialog);
        if (dialog.inAction()) {
            dialog
                .setKeyboard()
                .endAction()
                .sendMessage('Как скажешь. Если что, поддать парка можно с помощью /help.');
        }
    })

    .defineCommand(function (dialog) {
        var command = dialog.message.command;
        printFrom(dialog);
        dialog.sendMessage('Это я не понял. Отправь мне /help, что ли.');
    });

// ACTIONS //

TeaBot
    .defineAction('/requestfeature', function(dialog, message) {
        var description = message.getArgument();
        requestfeature(message, description, function(features) {
            dialog.endAction();
            dialog.sendMessage("Сохранил твое предложение. Парься дальше.");
        });
    })

    .defineAction('/reportbug', function(dialog, message) {
        var description = message.getArgument();
        reportbug(message, description, function(bug) {
            dialog.endAction();
            dialog.sendMessage("Сохранил твое сообщение. Легкого пара.");
        });
    })

    .defineAction('/trolluser', function(dialog, message) {

        var data = {};
        var keyboardPress = message.getArgument().split(" ")[1] || message.getArgument().split(" ")[0];

        console.log("--- got this when reacted to keyboard press: ", keyboardPress);

        if (keyboardPress === 'другого') {
            dialog
                .endAction(true)
                .setKeyboard()
                .startAction('/trolluser:manual')
                .sendMessage('OK, пиши сам руками тогда.');
        } else {
            userExists(keyboardPress, function(user) {
                if (user) {
                    data = prepareTempData(data, user);
                    dialog.setTempData('data', data);
                    dialog
                        .endAction(true)
                        .setKeyboard()
                        .startAction('/trolluser:phrase')
                        .sendMessage("Пиши фразу, чтобы добавить в его копилку. Когда он будет себя троллить, она будет выбираться случайным образом среди других.");

                } else {
                    dialog
                        .endAction(true)
                        .setKeyboard()
                        .startAction('/trolluser:contact')
                        .sendMessage("Запутался в своих записях. Пришли его телеграмовские контакты. Так надежнее.");
                }
            });
        }
    })

    .defineAction('/trolluser:manual', function(dialog, message) {
        var data = dialog.getTempData('data') || {};
        var userLastName = message.getArgument();
        userExists(userLastName, function(user) {
            if (user) {
                data = prepareTempData(data, user);
                dialog.setTempData('data', data);
                dialog
                    .endAction(true)
                    .setKeyboard()
                    .startAction('/trolluser:phrase')
                    .sendMessage("Пиши фразу, чтобы добавить в его копилку. Когда он будет себя троллить, она будет выбираться случайным образом среди других.");
            } else {
                dialog
                    .endAction(true)
                    .setKeyboard()
                    .startAction('/trolluser:contact')
                    .sendMessage("Не нашел такого в своих записях. Или просмотрел. Шли его телеграмовские контакты. Так надежнее.");
            }
        });
    })

    .defineAction('/trolluser:phrase', function(dialog, message) {
        var data = dialog.getTempData('data') || {};
        data.phrase = message.getArgument();
        trolluser.addTrollPhrase(data, function(user) {
            dialog
                .endAction()
                .setKeyboard();
            if (user) {
                dialog.sendMessage("Добавил, короче, ему в список.");
            } else {
                dialog.sendMessage("Что-то не получилось у меня. Попробуй еще раз как-нибудь.");
            }
        });
    })

    .defineAction('/trolluser:contact', function(dialog, message) {
        console.log("--- contact received: \n", message.contact);

        var data = dialog.getTempData('data') || {};

        if (!message.contact.user_id) {
            dialog
                .endAction()
                .setKeyboard()
                .sendMessage("Похоже, этого персонажа в Телеграме нет, спроси его напрямую сам.");
        } else {
            trolluser.addUserFromContact(message.contact, function(user) {
                if (user) {
                    data = prepareTempData(data, user);
                    dialog.setTempData('data', data);
                    dialog
                        .endAction(true)
                        .setKeyboard()
                        .startAction('/trolluser:phrase')
                        .sendMessage("Контакт запомнил. Пиши теперь фразу, чтобы добавить в его копилку. Когда он будет себя троллить, она будет выбираться случайным образом среди других.");
                } else {
                    dialog
                        .endAction()
                        .setKeyboard()
                        .sendMessage("Что-то пошло не так. Сложный юзер. Не смог запомнить.");
                }

            });
        }

    });

// Uncomment TeaBot.startPolling() and comment TeaBot.setWebhook
// to use polling method instead.

console.log(new Date().toISOString(), "BANYA BOT PROUDLY STARTED...");

if (process.env.OPENSHIFT_GEAR_DNS) {

    // Webhook option
    console.log("...AND USING WEBHOOK.");
    TeaBot.setWebhook('https://' + process.env.OPENSHIFT_GEAR_DNS + '/AAHaCgMCHBKK3Cy7UmI5TTBSrX4zGGpLv50');

    app.post('/AAHaCgMCHBKK3Cy7UmI5TTBSrX4zGGpLv50', function (req, res) {
      var message = req.body || false;
      if (message) {
        TeaBot.receive(message);
      }

      res.status(200).end();
    });

} else {

    // getUpdate polling option if not on OpenShift
    console.log("...AND USING POLLING.");
    TeaBot.startPolling();
}

// Environment settings for OpenShift and Heroku deployment

if (process.env.OPENSHIFT_NODEJS_PORT) {
    var port = process.env.OPENSHIFT_NODEJS_PORT;
} else {
    var port = process.env.PORT || 8080;
}

if (process.env.OPENSHIFT_NODEJS_IP) {
    var ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
}

if (ip_address) {
    app.listen(port, ip_address, function () {
    	console.log('Node.js listening on port ' + port + ' and ip address ' + ip_address + '...');
    });
} else {
    app.listen(port, function () {
    	console.log('Node.js listening on port ' + port + '...');
    });
}
<commit_msg>minor edits<commit_after>'use strict';

var util = require("util");
var mongoose = require('mongoose');
var path = process.cwd();
require('dotenv').load();
var app = require('express')();

if (process.env.MONGOLAB_URI) {
    mongoose.connect(process.env.MONGOLAB_URI);
} else {
    mongoose.connect(process.env.MONGO_URI);
}

var BanyaUsers = require('./app/models/banyaUsers.js');
var checkUser = require("./app/models/checkUser.js");

var start = require("./app/controllers/commands/start.js");
var help = require("./app/controllers/commands/help.js");
var motivateme = require("./app/controllers/commands/motivateme.js");
var trollme = require("./app/controllers/commands/trollme.js");
var trolluser = require("./app/controllers/commands/trolluser.js");
var requestfeature = require("./app/controllers/commands/requestfeature.js");
var reportbug = require("./app/controllers/commands/reportbug.js");

var TeaBot = require("teabot")(process.env.BOT_TOKEN, process.env.BOT_NAME);
TeaBot.use('analytics', require('teabot-botan')(process.env.BOTAN_TOKEN));

function printFrom(dialog) {
    var from = {
        id: dialog.message.from.id,
        username: dialog.message.from.username,
        first_name: dialog.message.from.first_name,
        last_name: dialog.message.from.last_name
    };
    var command = dialog.message.command;
    console.log(new Date().toISOString(), "command " + command + " request from: ", from.id, from.username, from.first_name, from.last_name);
}

function getName(dialog) {
    return dialog.message.from.first_name || dialog.message.from.username;
}

function getCurrentUsers(next) {
    BanyaUsers.find({}, function(err, users) {
        if (err) console.error(err);
        next(users);
    });
}

function userExists(name, next) {
    BanyaUsers.findOne({ $or: [ { 'user.secondName': name }, { 'user.firstName': name } ]}, function(err, user) {
        if (err) console.error(err);
        if (user) {
            console.log("--- found this user: ", user.userid, user.user.username, user.user.firstName, user.user.secondName);
        }
        if (next) { next(user); } else return user;
    });
}

function prepareTempData(data, user) {
    data.userid = user.userid;
    data.user = {
        firstName: user.user.firstName,
        secondName: user.user.secondName
    };
    return data;
}

TeaBot.onError(function (e) {
    console.error('TeaBot error:', e.stack);
});

// COMMANDS //

TeaBot
    .defineCommand('/start', function (dialog) {
        // console.log(util.inspect(dialog.message.from));
        printFrom(dialog);
        checkUser(dialog.message, function(user) {
            dialog
                .setKeyboard()
                .sendMessage(start(getName(dialog)));
        });

    })

    .defineCommand('/help', function (dialog) {
        printFrom(dialog);
        dialog
          .setKeyboard()
          .sendMessage(help(getName(dialog)));
    })

    .defineCommand('/motivateme', function (dialog) {
        printFrom(dialog);
        dialog
          .setKeyboard()
          .sendMessage(motivateme());
    })

    .defineCommand('/trollme', function (dialog) {
        printFrom(dialog);
        dialog.setKeyboard();
        trollme(dialog.message, function(response) {
            dialog.sendMessage(response);
        });
    })

    .defineCommand('/trolluser', function(dialog) {
        printFrom(dialog);
        dialog.startAction('/trolluser');
        getCurrentUsers(function(users) {
            var keyboard = [];
            users.forEach((el) => {
                if (el.userid != 170522191) {
                    keyboard.push(new Array((el.user.secondName) ? el.user.firstName + " " + el.user.secondName : el.user.firstName));
                }
            });
            keyboard.push(['другого']);
            keyboard.push(['/cancel']);

            dialog.setKeyboard(keyboard, true, true);
            dialog.sendMessage("Кого ты хочешь потроллить (скролл работает, если что)?");
        });

    })

    .defineCommand('/requestfeature', function (dialog) {
        printFrom(dialog);
        dialog.startAction('/requestfeature').sendMessage("Опиши предлагаемую фичу. Только коротко.");
    })

    .defineCommand('/reportbug', function (dialog) {
        printFrom(dialog);
        dialog.startAction('/reportbug').sendMessage("Опиши найденную ошибку. Только коротко.");
    })

    .defineCommand('/cancel', function (dialog) {
        printFrom(dialog);
        if (dialog.inAction()) {
            dialog
                .setKeyboard()
                .endAction()
                .sendMessage('Как скажешь. Если что, поддать парка можно с помощью /help.');
        }
    })

    .defineCommand(function (dialog) {
        var command = dialog.message.command;
        printFrom(dialog);
        dialog.sendMessage('Это я не понял. Отправь мне /help, что ли.');
    });

// ACTIONS //

TeaBot
    .defineAction('/requestfeature', function(dialog, message) {
        var description = message.getArgument();
        requestfeature(message, description, function(features) {
            dialog.endAction();
            dialog.sendMessage("Сохранил твое предложение. Парься дальше.");
        });
    })

    .defineAction('/reportbug', function(dialog, message) {
        var description = message.getArgument();
        reportbug(message, description, function(bug) {
            dialog.endAction();
            dialog.sendMessage("Сохранил твое сообщение. Легкого пара.");
        });
    })

    .defineAction('/trolluser', function(dialog, message) {

        var data = {};
        var keyboardPress = message.getArgument().split(" ")[1] || message.getArgument().split(" ")[0];

        console.log("--- got this when reacted to keyboard press: ", keyboardPress);

        if (keyboardPress === 'другого') {
            dialog
                .endAction(true)
                .setKeyboard()
                .startAction('/trolluser:manual')
                .sendMessage('OK, пиши сам руками тогда.');
        } else {
            userExists(keyboardPress, function(user) {
                if (user) {
                    data = prepareTempData(data, user);
                    dialog.setTempData('data', data);
                    dialog
                        .endAction(true)
                        .setKeyboard()
                        .startAction('/trolluser:phrase')
                        .sendMessage("Пиши фразу, чтобы добавить в его копилку. Когда он будет себя троллить, она будет выбираться случайным образом среди других.");

                } else {
                    dialog
                        .endAction(true)
                        .setKeyboard()
                        .startAction('/trolluser:contact')
                        .sendMessage("Запутался в своих записях. Пришли его телеграмовские контакты. Так надежнее.");
                }
            });
        }
    })

    .defineAction('/trolluser:manual', function(dialog, message) {
        var data = dialog.getTempData('data') || {};
        var userLastName = message.getArgument();
        userExists(userLastName, function(user) {
            if (user) {
                data = prepareTempData(data, user);
                dialog.setTempData('data', data);
                dialog
                    .endAction(true)
                    .setKeyboard()
                    .startAction('/trolluser:phrase')
                    .sendMessage("Пиши фразу, чтобы добавить в его копилку. Когда он будет себя троллить, она будет выбираться случайным образом среди других.");
            } else {
                dialog
                    .endAction(true)
                    .setKeyboard()
                    .startAction('/trolluser:contact')
                    .sendMessage("Не нашел такого в своих записях. Или просмотрел. Шли его телеграмовские контакты. Так надежнее.");
            }
        });
    })

    .defineAction('/trolluser:phrase', function(dialog, message) {
        var data = dialog.getTempData('data') || {};
        data.phrase = message.getArgument();
        trolluser.addTrollPhrase(data, function(user) {
            dialog
                .endAction()
                .setKeyboard();
            if (user) {
                dialog.sendMessage("Добавил, короче, ему в список.");
            } else {
                dialog.sendMessage("Что-то не получилось у меня. Попробуй еще раз как-нибудь.");
            }
        });
    })

    .defineAction('/trolluser:contact', function(dialog, message) {
        console.log("--- contact received: \n", message.contact);

        var data = dialog.getTempData('data') || {};

        if (!message.contact.user_id) {
            dialog
                .endAction()
                .setKeyboard()
                .sendMessage("Похоже, этого персонажа в Телеграме нет, спроси его напрямую сам.");
        } else {
            trolluser.addUserFromContact(message.contact, function(user) {
                if (user) {
                    data = prepareTempData(data, user);
                    dialog.setTempData('data', data);
                    dialog
                        .endAction(true)
                        .setKeyboard()
                        .startAction('/trolluser:phrase')
                        .sendMessage("Контакт запомнил. Пиши теперь фразу, чтобы добавить в его копилку. Когда он будет себя троллить, она будет выбираться случайным образом среди других.");
                } else {
                    dialog
                        .endAction()
                        .setKeyboard()
                        .sendMessage("Что-то пошло не так. Сложный юзер. Не смог запомнить.");
                }

            });
        }

    });

// Uncomment TeaBot.startPolling() and comment TeaBot.setWebhook
// to use polling method instead.

console.log(new Date().toISOString(), "BANYA BOT PROUDLY STARTED...");

if (process.env.OPENSHIFT_GEAR_DNS) {

    // Webhook option
    console.log("...AND USING WEBHOOK.");
    TeaBot.setWebhook('https://' + process.env.OPENSHIFT_GEAR_DNS + '/AAHaCgMCHBKK3Cy7UmI5TTBSrX4zGGpLv50');

    app.post('/AAHaCgMCHBKK3Cy7UmI5TTBSrX4zGGpLv50', function (req, res) {
      var message = req.body || false;
      console.log('...got a message...');
      if (message) {
        TeaBot.receive(message);
      }

      res.status(200).end();
    });

} else {

    // getUpdate polling option if not on OpenShift
    console.log("...AND USING POLLING.");
    TeaBot.startPolling();
}

// Environment settings for OpenShift and Heroku deployment

if (process.env.OPENSHIFT_NODEJS_PORT) {
    var port = process.env.OPENSHIFT_NODEJS_PORT;
} else {
    var port = process.env.PORT || 8080;
}

if (process.env.OPENSHIFT_NODEJS_IP) {
    var ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
}

if (ip_address) {
    app.listen(port, ip_address, function () {
    	console.log('Node.js listening on port ' + port + ' and ip address ' + ip_address + '...');
    });
} else {
    app.listen(port, function () {
    	console.log('Node.js listening on port ' + port + '...');
    });
}
<|endoftext|>


<commit_before>
var fs = require('fs'),
  http = require('http'),
  flash = require('connect-flash'),
  express = require('express'),
  passport = require('passport'),
  util = require('util'),
  LocalStrategy = require('passport-local').Strategy;

var fileUpload = require('./lib/file-upload.js');

GLOBAL.authed = GLOBAL.authed || {}; //FIXME  use auth scheme that works behind proxies
var users = require('./users.json').logins;

exports.start = start;

function start(config) {
  config.users = users;
  config.indexer = require('./lib/indexer.js');
  config.pageCache = require('./lib/pageCache.js');
  config.prefrontal = require('./lib/auth.js');
  config.consolidate = {
    process: function(uri, referer, is_html, pageBuffer, contentType, saveHeaders, browser_request) {
      var status = browser_request.proxy_received.statusCode;
      if (status != 200) {
        return;
      }
      // only index HTML with title
      var m = /<title>(.*)<\/title>/mi.exec(pageBuffer);
      if (m && m[1]) {
        var title = m[1].replace(/<.*?>/g);
        var psMember = browser_request.psMember.username;
        GLOBAL.config.pageCache.cache(uri, referer, is_html, pageBuffer, contentType, saveHeaders, browser_request);
        GLOBAL.config.indexer.indexPage({
          uri: uri, title: title, member: psMember, referer: referer, isHTML: browser_request.is_html, contents: pageBuffer, contentType: contentType, headers: saveHeaders});
      }
    }
  }
  // globally shared context
  GLOBAL.config = config;

// Passport stuff
function findById(id, fn) {
  var found = null;
  users.forEach(function(u) {
    if (u.id == id) {
      found = u;
    }
  });
  if (found) {
    fn(null, found);
  } else {
    fn(new Error('User ' + id + ' does not exist'));
  }
}

function findByUsername(username, fn) {
  for (var i = 0, len = users.length; i < len; i++) {
    var user = users[i];
    if (user.username === username) {
      return fn(null, user);
    }
  }
  return fn(null, null);
}

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

passport.deserializeUser(function(id, done) {
  findById(id, function (err, user) {
    done(err, user);
  });
});

passport.use(new LocalStrategy(
  function(username, password, done) {
    // asynchronous verification
    process.nextTick(function () {
      findByUsername(username, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
        if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
        if (!user.active) { return done(null, false, { message: 'Account not active' }); }
        return done(null, user);
      });
    });
  }
));

// Express stuff
var app = express();

app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.cookieParser());
  app.use(express.logger({stream: GLOBAL.config.logStream}));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.session({ secret: 'popsicle-fish' }));
  // Initialize Passport!  Also use passport.session() middleware, to support persistent login sessions (recommended).
  app.use(flash());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static('static'));
  app.use(require('connect-livereload')()); // FIXME
  app.enable('trust proxy');
});

app.all('/__wm/*', function(req, res, next) {
  if (req.user) {
//console.log('USER', req.user);
    next();
  } else {
    res.redirect("/login");
  }
});

app.get('/', function(req, res){
console.log('OO', req.session.user);
  if (req.user) {
    res.cookie('psMember', req.user.username, { maxAge: 900000 });
    res.cookie('psSession', req.user.id + '/' + new Date().getTime(), { maxAge: 900000 });

    res.redirect('/__wm/index.html');
//    res.render('index', { user: req.user.username });
  } else {
    res.render('login', { user: req.user, message: req.flash('error') });
  }
});

// used by client for identity
app.get('/member.js', function(req, res){
  res.render('memberjs', { user: req.user });
});

app.get('/login', function(req, res){
  res.render('login', { user: req.user, message: req.flash('error') });
});

app.post('/login',
  passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
  function(req, res) {
    GLOBAL.authed[req.ip] = req.user;
    console.log('OOOOOOO', req.ip, GLOBAL.authed);
    var oreq = req.headers['original-request'] || '/';
    if (oreq == 'undefined') { oreq = '/'; }
    res.redirect(GLOBAL.config.HOMEPAGE);
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

app.post('/upload', function(req, res) {
  fileUpload.uploadFile(req, function(err, resp) {
  console.log('GOGO', err, resp);
    GLOBAL.config.indexer.indexPage({
    uri: GLOBAL.config.HOMEPAGE + '/files/' + resp.fileName, isHTML: true, title: resp.title, member: req.user.username, content: resp.buffer,
      callback: function(err, res) {
        console.log('okiokok');
      }
    });
  });
});

var server = app.listen(9999);

var pubsub = require('./lib/pubsub.js');
pubsub.start(server);

var filterProxy = require('filter-proxy');

filterProxy.start(GLOBAL.config);

// interactive command line

repl = require("repl");
r = repl.start({ prompt: GLOBAL.config.project + "> ", useGlobal: true});
}
<commit_msg>fixing<commit_after>
var fs = require('fs'),
  http = require('http'),
  flash = require('connect-flash'),
  express = require('express'),
  passport = require('passport'),
  util = require('util'),
  LocalStrategy = require('passport-local').Strategy;

var fileUpload = require('./lib/file-upload.js');

GLOBAL.authed = GLOBAL.authed || {}; //FIXME  use auth scheme that works behind proxies
var users = require('./users.json').logins;

exports.start = start;

function start(config) {
  config.users = users;
  config.indexer = require('./lib/indexer.js');
  config.pageCache = require('./lib/pageCache.js');
  config.prefrontal = require('./lib/auth.js');
  config.consolidate = {
    process: function(uri, referer, is_html, pageBuffer, contentType, saveHeaders, browser_request) {
      var status = browser_request.proxy_received.statusCode;
      if (status != 200) {
        return;
      }
      // only index HTML with title
      var m = /<title>(.*)<\/title>/mi.exec(pageBuffer);
      if (m && m[1]) {
        var title = m[1].replace(/<.*?>/g);
        var psMember = browser_request.psMember.username;
        GLOBAL.config.pageCache.cache(uri, referer, is_html, pageBuffer, contentType, saveHeaders, browser_request);
        GLOBAL.config.indexer.indexPage({
          uri: uri, title: title, member: psMember, referer: referer, isHTML: browser_request.is_html, contents: pageBuffer, contentType: contentType, headers: saveHeaders});
      }
    }
  }
  // globally shared context
  GLOBAL.config = config;

// Passport stuff
function findById(id, fn) {
  var found = null;
  users.forEach(function(u) {
    if (u.id == id) {
      found = u;
    }
  });
  if (found) {
    fn(null, found);
  } else {
    fn(new Error('User ' + id + ' does not exist'));
  }
}

function findByUsername(username, fn) {
  for (var i = 0, len = users.length; i < len; i++) {
    var user = users[i];
    if (user.username === username) {
      return fn(null, user);
    }
  }
  return fn(null, null);
}

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

passport.deserializeUser(function(id, done) {
  findById(id, function (err, user) {
    done(err, user);
  });
});

passport.use(new LocalStrategy(
  function(username, password, done) {
    // asynchronous verification
    process.nextTick(function () {
      findByUsername(username, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
        if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
        if (!user.active) { return done(null, false, { message: 'Account not active' }); }
        return done(null, user);
      });
    });
  }
));

// Express stuff
var app = express();

app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.cookieParser());
  app.use(express.logger({stream: GLOBAL.config.logStream}));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.session({ secret: 'popsicle-fish' }));
  // Initialize Passport!  Also use passport.session() middleware, to support persistent login sessions (recommended).
  app.use(flash());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static('static'));
  app.enable('trust proxy');
});

app.all('/__wm/*', function(req, res, next) {
  if (req.user) {
//console.log('USER', req.user);
    next();
  } else {
    res.redirect("/login");
  }
});

app.get('/', function(req, res){
console.log('OO', req.session.user);
  if (req.user) {
    res.cookie('psMember', req.user.username, { maxAge: 900000 });
    res.cookie('psSession', req.user.id + '/' + new Date().getTime(), { maxAge: 900000 });

    res.redirect('/__wm/index.html');
//    res.render('index', { user: req.user.username });
  } else {
    res.render('login', { user: req.user, message: req.flash('error') });
  }
});

// used by client for identity
app.get('/member.js', function(req, res){
  res.render('memberjs', { user: req.user });
});

app.get('/login', function(req, res){
  res.render('login', { user: req.user, message: req.flash('error') });
});

app.post('/login',
  passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
  function(req, res) {
    GLOBAL.authed[req.ip] = req.user;
    console.log('OOOOOOO', req.ip, GLOBAL.authed);
    var oreq = req.headers['original-request'] || '/';
    if (oreq == 'undefined') { oreq = '/'; }
    res.redirect(GLOBAL.config.HOMEPAGE);
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

app.post('/upload', function(req, res) {
  fileUpload.uploadFile(req, function(err, resp) {
  console.log('GOGO', err, resp);
    GLOBAL.config.indexer.indexPage({
    uri: GLOBAL.config.HOMEPAGE + '/files/' + resp.fileName, isHTML: true, title: resp.title, member: req.user.username, content: resp.buffer,
      callback: function(err, res) {
        console.log('okiokok');
      }
    });
  });
});

var server = app.listen(9999);

var pubsub = require('./lib/pubsub.js');
pubsub.start(server);

var filterProxy = require('filter-proxy');

filterProxy.start(GLOBAL.config);

// interactive command line

repl = require("repl");
r = repl.start({ prompt: GLOBAL.config.project + "> ", useGlobal: true});
}
<|endoftext|>


<commit_before>'use strict';

var constant          = require('es5-ext/function/constant')
  , setPrototypeOf    = require('es5-ext/object/set-prototype-of')
  , ensureString      = require('es5-ext/object/validate-stringifiable-value')
  , ensureObject      = require('es5-ext/object/valid-object')
  , d                 = require('d')
  , deferred          = require('deferred')
  , serialize         = require('dbjs/_setup/serialize/value')
  , MongoClient       = require('mongodb').MongoClient
  , MongoCursor       = require('mongodb/lib/cursor')
  , PersistenceDriver = require('dbjs-persistence/abstract')

  , create = Object.create, promisify = deferred.promisify
  , getUndefined = constant(undefined)
  , getNull = constant(null)
  , connect = promisify(MongoClient.connect)
  , updateOpts = { upsert: true };

Object.defineProperties(MongoCursor.prototype, {
	nextPromised: d(promisify(MongoCursor.prototype.next)),
	toArrayPromised: d(promisify(MongoCursor.prototype.toArray)),
	closePromised: d(promisify(MongoCursor.prototype.close))
});

var buildUrl = function (conf) {
	var url = 'mongodb://';
	if (conf.user && conf.password) url += conf.user + ':' + conf.password + '@';
	url += (conf.host != null) ? conf.host : 'localhost';
	url += ':';
	url += (conf.port != null) ? conf.port : '27017';
	return url + '/' + conf.database;
};
var MongoDriver = module.exports = function (dbjs, data) {
	if (!(this instanceof MongoDriver)) return new MongoDriver(dbjs, data);
	ensureObject(data);
	ensureString(data.database);
	ensureString(data.collection);
	PersistenceDriver.call(this, dbjs, data);
	this.mongoDb = connect(buildUrl(data)).aside(null, this.emitError);
	this.collection = this.mongoDb.invokeAsync('collection', data.collection);
};
setPrototypeOf(MongoDriver, PersistenceDriver);

MongoDriver.prototype = Object.create(PersistenceDriver.prototype, {
	constructor: d(MongoDriver),

	// Any data
	_storeRaw: d(function (id, value) {
		var index;
		if (id[0] === '_') return this._storeCustom(id.slice(1), value);
		if (id[0] === '=') {
			index = id.lastIndexOf(':');
			return this._storeIndexedValue(id.slice(index + 1), id.slice(1, index), value);
		}
		return this.collection.invokeAsync('update', { _id: id },
			{ value: value.value, stamp: value.stamp }, updateOpts);
	}),

	// Database data
	_loadValue: d(function (id) {
		return this.collection.invokeAsync('find', { _id: id })(function (cursor) {
			return cursor.nextPromised()(function (record) {
				return cursor.closePromised()(record
					? this._importValue(id, record.value, record.stamp) : null);
			}.bind(this));
		}.bind(this));
	}),
	_loadObject: d(function (id) { return this._load({ _id: { $gte: id, $lt: id + '/\uffff' } }); }),
	_loadAll: d(function () { return this._load(); }),
	_storeEvent: d(function (event) {
		return this.collection.invokeAsync('update', { _id: event.object.__valueId__ }, {
			stamp: event.stamp,
			value: serialize(event.value)
		}, updateOpts);
	}),
	_storeEvents: d(function (events) { return deferred.map(events, this._storeEvent, this); }),

	// Indexed database data
	_getIndexedValue: d(function (objId, keyPath) {
		return this.collection.invokeAsync('find', { _id: '=' + keyPath + ':' + objId })(
			function (cursor) {
				return cursor.nextPromised()(function (record) {
					return cursor.closePromised()(record || getNull);
				});
			}
		);
	}),
	_getIndexedMap: d(function (keyPath) {
		var query = { _id: { $gte: '=' + keyPath + ':', $lt: '=' + keyPath + ':\uffff' } }
		  , map = create(null);
		return this.collection.invokeAsync('find', query)(function (cursor) {
			return cursor.toArrayPromised()(function (records) {
				records.forEach(function (record) {
					map[record._id.slice(record._id.lastIndexOf(':') + 1)] = record;
				}, this);
				return cursor.closePromised();
			}.bind(this));
		}.bind(this))(map);
	}),
	_storeIndexedValue: d(function (objId, keyPath, data) {
		return this.collection.invokeAsync('update', { _id: '=' + keyPath + ':' + objId }, {
			stamp: data.stamp,
			value: data.value
		}, updateOpts);
	}),

	// Custom data
	_getCustom: d(function (key) {
		return this.collection.invokeAsync('find', { _id: '_' + key })(function (cursor) {
			return cursor.nextPromised()(function (record) {
				return cursor.closePromised()(record ? record.value : getUndefined);
			});
		});
	}),
	_storeCustom: d(function (key, value) {
		if (value === undefined) return this.collection.invokeAsync('remove', { _id: '_' + key });
		return this.collection.invokeAsync('update', { _id: '_' + key }, { value: value }, updateOpts);
	}),

	// Storage import/export
	_exportAll: d(function (destDriver) {
		var count = 0;
		var promise = this.collection.invokeAsync('find')(function (cursor) {
			return cursor.toArrayPromised()(function (records) {
				return cursor.closePromised()(deferred.map(records, function (record) {
					if (!(++count % 1000)) promise.emit('progress');
					return destDriver._storeRaw(record._id, record);
				}, this));
			}.bind(this));
		}.bind(this));
		return promise;
	}),

	// Connection related
	_close: d(function () {
		return this.mongoDb.invokeAsync('close');
	}),

	// Driver specific
	_load: d(function (query) {
		var count = 0;
		var promise = this.collection.invokeAsync('find', query)(function (cursor) {
			return cursor.toArrayPromised()(function (records) {
				return cursor.closePromised()(records.map(function (record) {
					var event;
					if (record._id[0] === '=') return; // computed record
					if (record._id[0] === '_') return; // custom record
					event = this._importValue(record._id, record.value, record.stamp);
					if (event && !(++count % 1000)) promise.emit('progress');
					return event;
				}, this).filter(Boolean));
			}.bind(this));
		}.bind(this));
		return promise;
	})
});
<commit_msg>Update up to changes in dbsj-persistence<commit_after>'use strict';

var flatten           = require('es5-ext/array/#/flatten')
  , constant          = require('es5-ext/function/constant')
  , setPrototypeOf    = require('es5-ext/object/set-prototype-of')
  , ensureString      = require('es5-ext/object/validate-stringifiable-value')
  , ensureObject      = require('es5-ext/object/valid-object')
  , d                 = require('d')
  , deferred          = require('deferred')
  , serialize         = require('dbjs/_setup/serialize/value')
  , MongoClient       = require('mongodb').MongoClient
  , MongoCursor       = require('mongodb/lib/cursor')
  , PersistenceDriver = require('dbjs-persistence/abstract')

  , create = Object.create, promisify = deferred.promisify
  , getUndefined = constant(undefined)
  , getNull = constant(null)
  , connect = promisify(MongoClient.connect)
  , updateOpts = { upsert: true }
  , byStamp = function (a, b) { return a.data.stamp - b.data.stamp; };

Object.defineProperties(MongoCursor.prototype, {
	nextPromised: d(promisify(MongoCursor.prototype.next)),
	toArrayPromised: d(promisify(MongoCursor.prototype.toArray)),
	closePromised: d(promisify(MongoCursor.prototype.close))
});

var buildUrl = function (conf) {
	var url = 'mongodb://';
	if (conf.user && conf.password) url += conf.user + ':' + conf.password + '@';
	url += (conf.host != null) ? conf.host : 'localhost';
	url += ':';
	url += (conf.port != null) ? conf.port : '27017';
	return url + '/' + conf.database;
};
var MongoDriver = module.exports = function (dbjs, data) {
	if (!(this instanceof MongoDriver)) return new MongoDriver(dbjs, data);
	ensureObject(data);
	ensureString(data.database);
	ensureString(data.collection);
	PersistenceDriver.call(this, dbjs, data);
	this.mongoDb = connect(buildUrl(data)).aside(null, this.emitError);
	this.collection = this.mongoDb.invokeAsync('collection', data.collection);
};
setPrototypeOf(MongoDriver, PersistenceDriver);

MongoDriver.prototype = Object.create(PersistenceDriver.prototype, {
	constructor: d(MongoDriver),

	// Any data
	_getRaw: d(function (id) {
		var index;
		if (id[0] === '_') return this._getCustom(id.slice(1));
		if (id[0] === '=') {
			index = id.lastIndexOf(':');
			return this._getIndexedValue(id.slice(index + 1), id.slice(1, index));
		}
		return this.collection.invokeAsync('find', { _id: id })(function (cursor) {
			return cursor.nextPromised()(function (record) {
				return cursor.closePromised()(record);
			}.bind(this));
		}.bind(this));
	}),
	_getRawObject: d(function (objId) {
		return this._load({ _id: { $gte: objId, $lt: objId + '/\uffff' } });
	}),
	_storeRaw: d(function (id, value) {
		var index;
		if (id[0] === '_') return this._storeCustom(id.slice(1), value);
		if (id[0] === '=') {
			index = id.lastIndexOf(':');
			return this._storeIndexedValue(id.slice(index + 1), id.slice(1, index), value);
		}
		return this.collection.invokeAsync('update', { _id: id },
			{ value: value.value, stamp: value.stamp }, updateOpts);
	}),

	// Database data
	_loadAll: d(function () {
		return this._load().map(function (data) {
			return this._importValue(data.id, data.data.value, data.data.stamp);
		}.bind(this)).invoke(flatten);
	}),
	_storeEvent: d(function (event) {
		return this.collection.invokeAsync('update', { _id: event.object.__valueId__ }, {
			stamp: event.stamp,
			value: serialize(event.value)
		}, updateOpts);
	}),
	_storeEvents: d(function (events) { return deferred.map(events, this._storeEvent, this); }),

	// Indexed database data
	_getIndexedValue: d(function (objId, keyPath) {
		return this.collection.invokeAsync('find', { _id: '=' + keyPath + ':' + objId })(
			function (cursor) {
				return cursor.nextPromised()(function (record) {
					return cursor.closePromised()(record || getNull);
				});
			}
		);
	}),
	_getIndexedMap: d(function (keyPath) {
		var query = { _id: { $gte: '=' + keyPath + ':', $lt: '=' + keyPath + ':\uffff' } }
		  , map = create(null);
		return this.collection.invokeAsync('find', query)(function (cursor) {
			return cursor.toArrayPromised()(function (records) {
				records.forEach(function (record) {
					map[record._id.slice(record._id.lastIndexOf(':') + 1)] = record;
				}, this);
				return cursor.closePromised();
			}.bind(this));
		}.bind(this))(map);
	}),
	_storeIndexedValue: d(function (objId, keyPath, data) {
		return this.collection.invokeAsync('update', { _id: '=' + keyPath + ':' + objId }, {
			stamp: data.stamp,
			value: data.value
		}, updateOpts);
	}),

	// Custom data
	_getCustom: d(function (key) {
		return this.collection.invokeAsync('find', { _id: '_' + key })(function (cursor) {
			return cursor.nextPromised()(function (record) {
				return cursor.closePromised()(record ? record.value : getUndefined);
			});
		});
	}),
	_storeCustom: d(function (key, value) {
		if (value === undefined) return this.collection.invokeAsync('remove', { _id: '_' + key });
		return this.collection.invokeAsync('update', { _id: '_' + key }, { value: value }, updateOpts);
	}),

	// Storage import/export
	_exportAll: d(function (destDriver) {
		var count = 0;
		var promise = this.collection.invokeAsync('find')(function (cursor) {
			return cursor.toArrayPromised()(function (records) {
				return cursor.closePromised()(deferred.map(records, function (record) {
					if (!(++count % 1000)) promise.emit('progress');
					return destDriver._storeRaw(record._id, record);
				}, this));
			}.bind(this));
		}.bind(this));
		return promise;
	}),

	// Connection related
	_close: d(function () {
		return this.mongoDb.invokeAsync('close');
	}),

	// Driver specific
	_load: d(function (query) {
		var count = 0;
		var promise = this.collection.invokeAsync('find', query)(function (cursor) {
			return cursor.toArrayPromised()(function (records) {
				return cursor.closePromised()(records.map(function (record) {
					if (record._id[0] === '=') return; // computed record
					if (record._id[0] === '_') return; // custom record
					if (!(++count % 1000)) promise.emit('progress');
					return { id: record._id, data: record };
				}).filter(Boolean).sort(byStamp));
			}.bind(this));
		}.bind(this));
		return promise;
	})
});
<|endoftext|>