<commit_before>'use strict';

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _request = require('request');

var _request2 = _interopRequireDefault(_request);

var _cheerio = require('cheerio');

var _cheerio2 = _interopRequireDefault(_cheerio);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var GoogleScraper = exports.GoogleScraper = function () {
  function GoogleScraper(options) {
    _classCallCheck(this, GoogleScraper);

    this.options = options;
  }

  _createClass(GoogleScraper, [{
    key: 'getHtml',
    value: function getHtml() {
      var _this = this;

      return new Promise(function (resolve, reject) {
        (0, _request2.default)('http://www.google.fr/search?hl=' + _this.options.language + '&num=' + _this.options.results + '&q=' + _this.options.keyword, function (err, res, body) {
          if (err) {
            return reject(err);
          } else if (res.statusCode !== 200) {
            var error = new Error('Unexpected status code: ${res.statusCode}');
            error.res = res;
            return reject(error);
          }
          resolve(body);
        });
      });
    }
  }, {
    key: 'extractLink',
    value: function extractLink(html) {
      var arrayLinks = [];
      var $ = _cheerio2.default.load(html);
      $('h3.r a').each(function (i, link) {
        var linkClean = $(link).attr('href').match('(?=http|https).*(?=&sa)');
        if (linkClean !== null) {
          arrayLinks.push(linkClean[0]);
        }
      });
      return arrayLinks;
    }
  }, {
    key: 'getGoogleLinks',
    get: function get() {
      var _this2 = this;

      return new Promise(function (resolve, reject) {
        _this2.getHtml().then(function (body) {
          return resolve(_this2.extractLink(body));
        }).catch(function (err) {
          return reject(err);
        });
      });
    }
  }]);

  return GoogleScraper;
}();<commit_msg>remove lib/<commit_after><|endoftext|>


<commit_before>module.exports = {
  parser: 'babel-eslint',
  plugins: [
    'react'
  ],
  env: {
    browser: true,
    node: true,
    mocha: true
  },
  extends: ['plugin:react/recommended'],
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true
    }
  },
  rules: {
    'react/no-danger': 1,
    'react/no-did-mount-set-state': 1,
    'react/no-did-update-set-state': 1,
    'react/no-direct-mutation-state': 1,
    'react/jsx-no-duplicate-props': 1,
    'react/self-closing-comp': 1,
    'react/jsx-uses-react': 1,
    'react/jsx-uses-vars': 1,
    'react/jsx-wrap-multilines': 1,
    'react/jsx-indent-props': [1, 2]
  }
};
<commit_msg>Adds more react rules.<commit_after>module.exports = {
  parser: 'babel-eslint',
  plugins: [
    'react'
  ],
  env: {
    browser: true,
    node: true,
    mocha: true
  },
  extends: ['plugin:react/recommended'],
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true
    }
  },
  rules: {
    'react/no-danger': 1,
    'react/no-did-mount-set-state': 1,
    'react/no-did-update-set-state': 1,
    'react/no-direct-mutation-state': 1,
    'react/no-typos': 1,
    'react/no-unused-state': 1,
    'react/no-unused-prop-types': 1,
    'react/jsx-no-duplicate-props': 1,
    'react/self-closing-comp': 1,
    'react/sort-comp': 1,
    'react/jsx-uses-react': 1,
    'react/jsx-uses-vars': 1,
    'react/jsx-wrap-multilines': 1,
    'react/jsx-indent-props': [1, 2]
  }
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var debug = require("debug")("search");
var trie = require("trie-search");
var slug = require("slug");
var uniq = require("unq");
var dur = require("dur");

function search(opt, api){

	if (!(this instanceof search)) return new search(opt, api);
	var self = this;

	self.opt = opt||{};
	self.opt.reindex = (self.opt.hasOwnProperty("reindex") && self.opt.reindex) ? dur(self.opt.reindex) : dur("5m");

	self.api = api;
	self.trie = new trie(['name', 'aliases'], {min: 3, indexField: 'id'});

	self.rels = {};
	self.dtindex = {};
	self.ftindex = {};

	// reindexing
	self.index();
	self.reindex = setInterval(function(){
		self.index();
	}, self.opt.reindex);

	return this;
};

// entity autocomplete
search.prototype.autocomplete = function(str, fn){
	var self = this;
	fn(null, self.trie.get(str));
	return this;
};

// all data type sets
search.prototype.datatypes = function(fn){
	var self = this;
	fn(null, self.dtindex);
	return this;
};

// array of field types
search.prototype.fieldtypes = function(fn){
	var self = this;
	fn(null, self.ftindex);
	return this;
};

// reindex search data
search.prototype.index = function(fn){
	var self = this;
	if (typeof fn !== "function") var fn = function(){};

	// get relations for index
	self.api.rels(function(err, rels){
		if (err) debug("rel index error: %s", err);
		if (err) return fn(err);
		self.rels = rels;

		// get entities for index
		self.api.ents(function(err, result){
			if (err) debug("ent index error: %s", err);
			if (err) return fn(err);
			self.trie.reset();

			// temporary data type index
			var _dtindex = [];
			var _ftindex = {};

			// autocomplete index
			result.forEach(function(item){

				self.trie.add({
					id: item._id,
					name: item.name,
					aliases: item.aliases,
					relations: (self.rels.hasOwnProperty(item._id) ? self.rels[item._id].length : 0)
				});

				// data type index
				item.data.forEach(function(d){
					_dtindex.push(JSON.stringify({
						key: d.key,
						name: d.desc,
						format: d.format,
						mode: item.type
					}));

					// field type index
					if (!_ftindex.hasOwnProperty(d.format)) _ftindex[d.format] = true;

				});

			});

			// FIXME: rel indexing

			// make unique data type index
			self.dtindex = uniq(_dtindex).map(function(d){ return JSON.parse(d); }).sort(function(a,b){
				return (a.key.localeCompare(b.key));
			});
			self.ftindex = Object.keys(_ftindex);

			debug("ent indexing done");
			fn(null);
		});
	});
	return this;
};

module.exports = search;
<commit_msg>+relations, interface prototype<commit_after>#!/usr/bin/env node

var debug = require("debug")("search");
var trie = require("trie-search");
var slug = require("slug");
var uniq = require("unq");
var dur = require("dur");

function search(opt, api){

	if (!(this instanceof search)) return new search(opt, api);
	var self = this;

	self.opt = opt||{};
	self.opt.reindex = (self.opt.hasOwnProperty("reindex") && self.opt.reindex) ? dur(self.opt.reindex) : dur("5m");

	self.api = api;
	self.trie = new trie(['name', 'aliases'], {min: 3, indexField: 'id'});

	self.rels = {};
	self.reltypes = [];
	self.dtindex = {};
	self.ftindex = {};

	// reindexing
	self.reindex(function(err){
		if (err) debug("ERR: %s", err);
	});
	(setInterval(function(){
		self.reindex();
	}, self.opt.reindex)).unref();

	return this;
};

// ✓ entity autocomplete
search.prototype.autocomplete = function(str, fn){
	var self = this;
	fn(null, self.trie.get(str));
	return this;
};

// find route between entities
search.prototype.route = function(fn){};

// search in data types
search.prototype.entsearch = function(fn){

};

// search for relations
search.prototype.relsearch = function(fn){

};

// search in data types
search.prototype.datasearch = function(q, fn){

};

// ✓ all types of relations
search.prototype.reltypes = function(fn){
	var self = this;
	fn(null, self.reltypes);
	return this;
};

// ✓ all data type sets
search.prototype.datatypes = function(fn){
	var self = this;
	fn(null, self.dtindex);
	return this;
};

// ✓ array of field types
search.prototype.fieldtypes = function(fn){
	var self = this;
	fn(null, self.ftindex);
	return this;
};

// ✓ reindex search data
search.prototype.reindex = function(fn){
	var self = this;
	if (typeof fn !== "function") var fn = function(){};

	// get relations for index
	self.api.rels(function(err, rels){
		if (err) debug("rel index error: %s", err);
		if (err) return fn(err);
		self.rels = rels;

		// get entities for index
		self.api.ents(function(err, ents){
			if (err) debug("[reindex] ent index error: %s", err);
			if (err) return fn(err);

			// rel indexing
			self.api.rels_full(function(err, rels){
				if (err) debug("[reindex] rel index error: %s", err);
				if (err) return fn(err);

				self.trie.reset();

				// temporary data type index
				var _dtindex = {};
				var _ftindex = {};
				var _reltypes = {};

				// autocomplete index
				debug("[reindex] preparing entities");
				ents.forEach(function(item){

					self.trie.add({
						id: item._id,
						name: item.name,
						aliases: item.aliases,
						relations: (self.rels.hasOwnProperty(item._id) ? self.rels[item._id].length : 0)
					});

					// data type index
					item.data.forEach(function(d){
						if (d.value !== null && typeof d.value === "object") {
							Object.keys(d.value).forEach(function(k){
								// add to data type index
								_dtindex[[item.type, d.key+"."+k, d.format].join("-")] = {
									key: d.key+"."+k,
									name: d.desc,
									format: d.format,
									mode: item.type
								};
							});
						} else {
							// add to data type index
							_dtindex[[item.type, d.key, d.format].join("-")] = {
								key: d.key,
								name: d.desc,
								format: d.format,
								mode: item.type
							};
						}

						// field type index
						if (!_ftindex.hasOwnProperty(d.format)) _ftindex[d.format] = true;

					});

				});

				debug("[reindex] preparing relations");
				rels.forEach(function(item){

					// data type index
					item.data.forEach(function(d){
						if (d.value !== null && typeof d.value === "object") {
							Object.keys(d.value).forEach(function(k){
								// add to data type index
								_dtindex[[item.type, d.key+"."+k, d.format].join("-")] = {
									key: d.key+"."+k,
									name: d.desc,
									format: d.format,
									mode: item.type
								};
							});
						} else {
							// add to data type index
							_dtindex[[item.type, d.key, d.format].join("-")] = {
								key: d.key,
								name: d.desc,
								format: d.format,
								mode: item.type
							};
						}

						// field type index
						if (!_ftindex.hasOwnProperty(d.format)) _ftindex[d.format] = true;

					});

					// relation type index
					if (!_reltypes.hasOwnProperty(item.type)) _reltypes[item.type] = true;

				});

				// make unique data type index
				debug("[reindex] reindexing data type index");
				self.dtindex = Object.keys(_dtindex).map(function(k){ return _dtindex[k]; }).sort(function(a,b){
					return (a.key.localeCompare(b.key));
				});
				self.ftindex = Object.keys(_ftindex);
				self.reltypes = Object.keys(_reltypes);

			});
		});
	});
	return this;
};

module.exports = search;
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  plugins: ['react'],
  parserOptions: {
    ecmaFeatures: {
      jsx: true
    }
  },
  rules: {
    // https://github.com/yannickcr/eslint-plugin-react
    'react/jsx-boolean-value': 'error',
    'react/jsx-no-duplicate-props': ['error', { ignoreCase: true }],
    'react/jsx-filename-extension': ['error', { extensions: ['.js'] }],
    'react/jsx-no-literals': 'warn',
    'react/jsx-no-undef': 'error',
    'react/jsx-uses-react': 'error',
    'react/jsx-uses-vars': 'error',
    'react/jsx-handler-names': 'warn',
    'react/jsx-no-bind': 'warn',
    'react/no-danger': 'warn',
    'react/no-multi-comp': ['error', { ignoreStateless: true }],
    'react/no-did-mount-set-state': 'error',
    'react/no-did-update-set-state': 'error',
    'react/no-direct-mutation-state': 'error',
    'react/no-deprecated': 'error',
    'react/no-unknown-property': 'error',
    'react/react-in-jsx-scope': 'warn',
    'react/self-closing-comp': 'error',
    'react/sort-comp': [
      'warn',
      {
        order: [
          'static-variables',
          'static-methods',
          'lifecycle',
          'everything-else',
          'render'
        ]
      }
    ]
  },
  overrides: [
    {
      files: '*.{ts,tsx}',
      rules: {
        'react/jsx-filename-extension': 'off'
      }
    }
  ]
};
<commit_msg>inherit from `prettier/react`<commit_after>'use strict';

module.exports = {
  extends: 'prettier/react',
  plugins: ['react'],
  parserOptions: {
    ecmaFeatures: {
      jsx: true
    }
  },
  rules: {
    // https://github.com/yannickcr/eslint-plugin-react
    'react/jsx-boolean-value': 'error',
    'react/jsx-no-duplicate-props': ['error', { ignoreCase: true }],
    'react/jsx-filename-extension': ['error', { extensions: ['.js'] }],
    'react/jsx-no-literals': 'warn',
    'react/jsx-no-undef': 'error',
    'react/jsx-uses-react': 'error',
    'react/jsx-uses-vars': 'error',
    'react/jsx-handler-names': 'warn',
    'react/jsx-no-bind': 'warn',
    'react/no-danger': 'warn',
    'react/no-multi-comp': ['error', { ignoreStateless: true }],
    'react/no-did-mount-set-state': 'error',
    'react/no-did-update-set-state': 'error',
    'react/no-direct-mutation-state': 'error',
    'react/no-deprecated': 'error',
    'react/no-unknown-property': 'error',
    'react/react-in-jsx-scope': 'warn',
    'react/self-closing-comp': 'error',
    'react/sort-comp': [
      'warn',
      {
        order: [
          'static-variables',
          'static-methods',
          'lifecycle',
          'everything-else',
          'render'
        ]
      }
    ]
  },
  overrides: [
    {
      files: '*.{ts,tsx}',
      rules: {
        'react/jsx-filename-extension': 'off'
      }
    }
  ]
};
<|endoftext|>


<commit_before>'use strict';
const http	= require('http');
const fs		= require('fs');
const path	= require('path');

const loadSite = (sitePath, cb) => {
	fs.stat(sitePath, (err, info) => {
		if (err) {
			cb(err);
			return;
		}
		if (!info.isDirectory()) {
			cb(new Error(`Site path is not a directory: ${sitePath}`));
		}
		try {
			var cacheKey = require.resolve(sitePath);
			if (require.cache[cacheKey]) {
				delete require.cache[cacheKey];
			}
			cb(null, require(sitePath));
		} catch (e) {
			cb(new Error(`Cannot load site from ${sitePath}: ${e.message}`));
		}
	});
};

const loadSitesFromPath = (sitesPath, cb) => {
	fs.stat(sitesPath, (err, info) => {
		if (err) {
			cb(err);
			return;
		}
		if (!info.isDirectory()) {
			cb(new Error(`Sites path is not a directory: ${sitesPath}`));
			return;
		}
		fs.readdir(sitesPath, (err, files) => {
			if (err) {
				cb(err);
				return;
			}
			let sites = {};
			let filesLeft = files.length;
			const checkAllLoaded = () => {
				if (filesLeft > 0) {
					return;
				}
				cb(null, sites);
			};
			files.forEach(file => {
				let sitePath = path.join(process.env.PWD, sitesPath, file);
				loadSite(sitePath, (err, site) => {
					if (!err) {
						sites[file] = site;
					}
					--filesLeft;
					checkAllLoaded();
				});
			});
		});
	});
};

const createServer = (config) => {
	config = Object.assign(require('./config.js'), config);
	let sites = {};
	if (config.port < 1024 && process.geteuid() != 0) {
		throw new Error('Must be run as root to listen to port < 1024.');
	}
	const loadSites = () => {
		loadSitesFromPath(config.sites, (err, loadedSites) => {
			if (err) {
				console.log(err);
				return;
			}
			sites = loadedSites;
		});
	};
	const admin = (req, res) => {
		var command = req.url.replace(/^\//,'');
		if (command == 'reload') {
			console.log('Reloading sites');
			loadSites();
		}
		res.end('ok');
	}
	const isAdminHost = (host) => {
		host = host.toLowerCase();
		if (config.adminsite instanceof RegExp) {
			return config.adminsite.test(host);
		}
		return host == config.adminsite;
	};
	const server = http.createServer((req, res) => {
		if (isAdminHost(req.headers.host)) {
			admin(req, res);
			return;
		}
		const site = req.headers.host.toLowerCase().replace(/^www\.|:\d+$/g, '');
		console.log(`Requested site: ${site}`);
		if (!sites.hasOwnProperty(site)) {
			console.log(`No site site '${site}'. Responding with 404.`);
			res.statusCode = 404;
			res.end('No such site here :-(');
		} else {
			try {
				sites[site](req, res);
			} catch(err) {
				console.log(`Error in '${site}': ${err}`);
				res.statusCode = 500;
				res.end('Ouch, internal server error!');
			}
		}
	});
	server.listen(config.port, () => {
		if (config.port < 1024) {
			try {
				process.setgid(config.group);
				process.setuid(config.user);
				console.log(`Runnings as ${config.user}`);
			} catch (err) {
				throw new Error('Failed to drop privileges.');
			}
		}
		console.log(`Server up and running on port ${config.port}`);
	});
	loadSites();
	return {};
};

module.exports = createServer;
<commit_msg>Removed PWD from sites path<commit_after>'use strict';
const http	= require('http');
const fs		= require('fs');
const path	= require('path');

const loadSite = (sitePath, cb) => {
	fs.stat(sitePath, (err, info) => {
		if (err) {
			cb(err);
			return;
		}
		if (!info.isDirectory()) {
			cb(new Error(`Site path is not a directory: ${sitePath}`));
		}
		try {
			var cacheKey = require.resolve(sitePath);
			if (require.cache[cacheKey]) {
				delete require.cache[cacheKey];
			}
			cb(null, require(sitePath));
		} catch (e) {
			cb(new Error(`Cannot load site from ${sitePath}: ${e.message}`));
		}
	});
};

const loadSitesFromPath = (sitesPath, cb) => {
	fs.stat(sitesPath, (err, info) => {
		if (err) {
			cb(err);
			return;
		}
		if (!info.isDirectory()) {
			cb(new Error(`Sites path is not a directory: ${sitesPath}`));
			return;
		}
		fs.readdir(sitesPath, (err, files) => {
			if (err) {
				cb(err);
				return;
			}
			let sites = {};
			let filesLeft = files.length;
			const checkAllLoaded = () => {
				if (filesLeft > 0) {
					return;
				}
				cb(null, sites);
			};
			files.forEach(file => {
				let sitePath = path.join(sitesPath, file);
				loadSite(sitePath, (err, site) => {
					if (!err) {
						sites[file] = site;
					}
					--filesLeft;
					checkAllLoaded();
				});
			});
		});
	});
};

const createServer = (config) => {
	config = Object.assign(require('./config.js'), config);
	let sites = {};
	if (config.port < 1024 && process.geteuid() != 0) {
		throw new Error('Must be run as root to listen to port < 1024.');
	}
	const loadSites = () => {
		loadSitesFromPath(config.sites, (err, loadedSites) => {
			if (err) {
				console.log(err);
				return;
			}
			sites = loadedSites;
		});
	};
	const admin = (req, res) => {
		var command = req.url.replace(/^\//,'');
		if (command == 'reload') {
			console.log('Reloading sites');
			loadSites();
		}
		res.end('ok');
	}
	const isAdminHost = (host) => {
		host = host.toLowerCase();
		if (config.adminsite instanceof RegExp) {
			return config.adminsite.test(host);
		}
		return host == config.adminsite;
	};
	const server = http.createServer((req, res) => {
		if (isAdminHost(req.headers.host)) {
			admin(req, res);
			return;
		}
		const site = req.headers.host.toLowerCase().replace(/^www\.|:\d+$/g, '');
		console.log(`Requested site: ${site}`);
		if (!sites.hasOwnProperty(site)) {
			console.log(`No site site '${site}'. Responding with 404.`);
			res.statusCode = 404;
			res.end('No such site here :-(');
		} else {
			try {
				sites[site](req, res);
			} catch(err) {
				console.log(`Error in '${site}': ${err}`);
				res.statusCode = 500;
				res.end('Ouch, internal server error!');
			}
		}
	});
	server.listen(config.port, () => {
		if (config.port < 1024) {
			try {
				process.setgid(config.group);
				process.setuid(config.user);
				console.log(`Runnings as ${config.user}`);
			} catch (err) {
				throw new Error('Failed to drop privileges.');
			}
		}
		console.log(`Server up and running on port ${config.port}`);
	});
	loadSites();
	return {};
};

module.exports = createServer;
<|endoftext|>


<commit_before>"use strict";
/** @jsx React.DOM */

jest.dontMock("../index.js");
describe("index", function() {
  it("changes the text after click", function() {
    var index = require("../index");

    expect(index).toBeDefined();
    expect(index.ToastContainer).toBeDefined();
    expect(index.ToastMessage).toBeDefined();
  });
});
<commit_msg>chore(index-test): compile jsx to js<commit_after>"use strict";

jest.dontMock("../index.js");
describe("index", function() {
  it("changes the text after click", function() {
    var index = require("../index");

    expect(index).toBeDefined();
    expect(index.ToastContainer).toBeDefined();
    expect(index.ToastMessage).toBeDefined();
  });
});
<|endoftext|>


<commit_before>module.exports = {
  plugins: ['react'],
  parserOptions: {
    ecmaFeatures: {
      jsx: true
    }
  },
  extends: [
    __dirname + '/browser.js'
  ],
  rules: {
    'react/display-name': [2, {ignoreTranspilerName: true}],
    'react/no-deprecated': 2,
    'react/no-did-mount-set-state': 2,
    'react/no-did-update-set-state': 2,
    'react/no-direct-mutation-state': 2,
    'react/no-find-dom-node': 2,
    'react/no-is-mounted': 2,
    'react/no-multi-comp': 2,
    'react/no-render-return-value': 2,
    'react/no-string-refs': 1,
    'react/no-unknown-property': 2,
    'react/prefer-es6-class': [2, 'always'],
    'react/prefer-stateless-function': 1,
    'react/prop-types': 2,
    'react/react-in-jsx-scope': 2,
    'react/require-render-return': 2,
    'react/self-closing-comp': 2,
    'react/sort-comp': 2,
    'react/jsx-curly-spacing': [2, 'never'],
    'react/jsx-equals-spacing': [2, 'never'],
    'react/jsx-indent': [2, 2],
    'react/jsx-indent-props': [2, 2],
    'react/jsx-key': 2,
    'react/jsx-no-bind': [2, {ignoreRefs: true}],
    'react/jsx-no-comment-textnodes': 2,
    'react/jsx-no-duplicate-props': 2,
    'react/jsx-no-undef': 2,
    'react/jsx-pascal-case': 2,
    'react/jsx-space-before-closing': [2, 'always'],
    'react/jsx-uses-react': 2,
    'react/jsx-uses-vars': 2,
    'react/jsx-wrap-multilines': 2
  }
};
<commit_msg>feat: change no-multi-comp to ignoreStateless<commit_after>module.exports = {
  plugins: ['react'],
  parserOptions: {
    ecmaFeatures: {
      jsx: true
    }
  },
  extends: [
    __dirname + '/browser.js'
  ],
  rules: {
    'react/display-name': [2, {ignoreTranspilerName: true}],
    'react/no-deprecated': 2,
    'react/no-did-mount-set-state': 2,
    'react/no-did-update-set-state': 2,
    'react/no-direct-mutation-state': 2,
    'react/no-find-dom-node': 2,
    'react/no-is-mounted': 2,
    'react/no-multi-comp': [2, {ignoreStateless: true}],
    'react/no-render-return-value': 2,
    'react/no-string-refs': 1,
    'react/no-unknown-property': 2,
    'react/prefer-es6-class': [2, 'always'],
    'react/prefer-stateless-function': 1,
    'react/prop-types': 2,
    'react/react-in-jsx-scope': 2,
    'react/require-render-return': 2,
    'react/self-closing-comp': 2,
    'react/sort-comp': 2,
    'react/jsx-curly-spacing': [2, 'never'],
    'react/jsx-equals-spacing': [2, 'never'],
    'react/jsx-indent': [2, 2],
    'react/jsx-indent-props': [2, 2],
    'react/jsx-key': 2,
    'react/jsx-no-bind': [2, {ignoreRefs: true}],
    'react/jsx-no-comment-textnodes': 2,
    'react/jsx-no-duplicate-props': 2,
    'react/jsx-no-undef': 2,
    'react/jsx-pascal-case': 2,
    'react/jsx-space-before-closing': [2, 'always'],
    'react/jsx-uses-react': 2,
    'react/jsx-uses-vars': 2,
    'react/jsx-wrap-multilines': 2
  }
};
<|endoftext|>


<commit_before>var fs = require('fs');
var express = require('express');
var app = express();
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var everyauth = require('everyauth');
var githubIssues = require('../get_issues');
var githubOrgs = require('../get_orgs');

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

everyauth.debug = true;
everyauth.github
  .appId(config.gh_clientId)
  .appSecret(config.gh_secret)
  .entryPath('/auth/github')
  .callbackPath('/auth/github/callback')
  .scope('repo')
  .findOrCreateUser( function (session, accessToken, accessTokenExtra, githubUserMetadata) {
    session.oauth = accessToken;
	session.uid = githubUserMetadata.login;
	return session.uid;
  })
  .redirectPath('/');

// everyauth.everymodule.handleLogout( function (req, res) {
//   req.session.oauth = null;
//   req.session.uid = null;

//   req.logout();

//   res.redirect('/test');
// });

app.use(cookieParser());
app.use(bodyParser());

app.use(session({secret: config.gh_secret}));

app.use(everyauth.middleware());

var checkOAuth = function (req, res, next) {
	if (!req.session.oauth || !req.session.uid) {
		return res.redirect('/launch.html');
	} else {
		next();
	}
};

var checkLogin = function (req, res, next) {
	if (!req.session.source) {
		return res.redirect('/login.html');
	} else {
		next();
	}
};

app.get('/graph-data.json', checkOAuth, checkLogin, function (req, res) {

	githubIssues.getIssues(req.session, function (err, data){
		if (err) {
			console.log(err);
			res.send(500, "error");
			return;
		}
		//console.log(data);
		res.json(data);
	});
});

app.get('/orgs.json', checkOAuth, function (req, res) {

	githubOrgs.getOrgs(req.session.uid, req.session.oauth, function (err, data){
		if (err) {
			console.log(err);
			res.send(500, "error");
			return;
		}
		//console.log(data);
		res.json(data);
	});
});

app.get('/login.html', checkOAuth, function (req, res, next){
	next();
});

app.post('/login.html', function (req, res) {
	req.session.source = req.body.source;
	req.session.sname = req.body.sname;
	res.redirect('/');
});

app.get('/', checkOAuth, checkLogin, function (req, res, next){
	next();
});

app.use(express.static(__dirname + '/../public'));

app.get('/:query', function (req, res, next) {
	console.log(req.params.query);
	req.session.source = 3;
	req.session.sname = req.params.query;
	res.redirect('/');
});

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function (){
	console.log('Listening on port %d', server.address().port);
});<commit_msg>fix error when session is clear<commit_after>var fs = require('fs');
var path = require('path');
var express = require('express');
var app = express();
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var everyauth = require('everyauth');
var githubIssues = require('../get_issues');
var githubOrgs = require('../get_orgs');

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

everyauth.debug = true;
everyauth.github
  .appId(config.gh_clientId)
  .appSecret(config.gh_secret)
  .entryPath('/auth/github')
  .callbackPath('/auth/github/callback')
  .scope('repo')
  .findOrCreateUser( function (session, accessToken, accessTokenExtra, githubUserMetadata) {
    session.oauth = accessToken;
	session.uid = githubUserMetadata.login;
	return session.uid;
  })
  .redirectPath('/');

// everyauth.everymodule.handleLogout( function (req, res) {
//   req.session.oauth = null;
//   req.session.uid = null;

//   req.logout();

//   res.redirect('/test');
// });

app.use(cookieParser());
app.use(bodyParser());

app.use(session({secret: config.gh_secret}));

app.use(everyauth.middleware());

var checkOAuth = function (req, res, next) {
	if (!req.session.oauth || !req.session.uid) {
		return res.redirect('/launch.html');
	} else {
		next();
	}
};

var checkLogin = function (req, res, next) {
	if (!req.session.source) {
		return res.redirect('/login.html');
	} else {
		next();
	}
};

app.get('/graph-data.json', checkOAuth, checkLogin, function (req, res) {

	githubIssues.getIssues(req.session, function (err, data){
		if (err) {
			console.log(err);
			res.send(500, "error");
			return;
		}
		//console.log(data);
		res.json(data);
	});
});

app.get('/orgs.json', checkOAuth, function (req, res) {

	githubOrgs.getOrgs(req.session.uid, req.session.oauth, function (err, data){
		if (err) {
			console.log(err);
			res.send(500, "error");
			return;
		}
		//console.log(data);
		res.json(data);
	});
});

app.get('/login.html', checkOAuth, function (req, res, next){
	next();
});

app.post('/login.html', function (req, res) {
	req.session.source = req.body.source;
	req.session.sname = req.body.sname;
	res.redirect('/');
});

app.get('/', checkOAuth, checkLogin, function (req, res, next){
	res.sendfile(path.resolve(__dirname+"/../public/index.html"));
});

app.use(express.static(__dirname + '/../public'));

app.get('/:query', function (req, res, next) {
	console.log(req.params.query);
	req.session.source = 3;
	req.session.sname = req.params.query;
	res.redirect('/');
});

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function (){
	console.log('Listening on port %d', server.address().port);
});<|endoftext|>


<commit_before>!function (name, definition) {
  if (typeof module != 'undefined') module.exports = definition()
  else if (typeof define == 'function' && typeof define.amd == 'object') define(definition)
  else this[name] = definition()
}('domready', function (ready) {

  var fns = [], fn, f = false
    , doc = document
    , testEl = doc.documentElement
    , hack = testEl.doScroll
    , domContentLoaded = 'DOMContentLoaded'
    , addEventListener = 'addEventListener'
    , onreadystatechange = 'onreadystatechange'
    , loaded = /^loade|c/.test(doc.readyState)

  function flush(f) {
    loaded = 1
    while (f = fns.shift())
      try { f() } catch (e) {}
  }

  doc[addEventListener] && doc[addEventListener](domContentLoaded, fn = function () {
    doc.removeEventListener(domContentLoaded, fn, f)
    flush()
  }, f)

  hack && doc.attachEvent(onreadystatechange, (fn = function () {
    if (/^c/.test(doc.readyState)) {
      doc.detachEvent(onreadystatechange, fn)
      flush()
    }
  }))

  return (ready = hack ?
    function (fn) {
      self != top ?
        loaded ? fn() : fns.push(fn) :
        function () {
          try {
            testEl.doScroll('left')
          } catch (e) {
            return setTimeout(function() { ready(fn) }, 50)
          }
          fn()
        }()
    } :
    function (fn) {
      loaded ? fn() : fns.push(fn)
    })
})
<commit_msg>updated to latest domReady<commit_after>/*!
  * domready (c) Dustin Diaz 2012 - License MIT
  */
!function (name, definition) {
  if (typeof module != 'undefined') module.exports = definition()
  else if (typeof define == 'function' && typeof define.amd == 'object') define(definition)
  else this[name] = definition()
}('domready', function (ready) {

  var fns = [], fn, f = false
    , doc = document
    , testEl = doc.documentElement
    , hack = testEl.doScroll
    , domContentLoaded = 'DOMContentLoaded'
    , addEventListener = 'addEventListener'
    , onreadystatechange = 'onreadystatechange'
    , readyState = 'readyState'
    , loaded = /^loade|c/.test(doc[readyState])

  function flush(f) {
    loaded = 1
    while (f = fns.shift()) f()
  }

  doc[addEventListener] && doc[addEventListener](domContentLoaded, fn = function () {
    doc.removeEventListener(domContentLoaded, fn, f)
    flush()
  }, f)

  hack && doc.attachEvent(onreadystatechange, fn = function () {
    if (/^c/.test(doc[readyState])) {
      doc.detachEvent(onreadystatechange, fn)
      flush()
    }
  })

  return (ready = hack ?
    function (fn) {
      self != top ?
        loaded ? fn() : fns.push(fn) :
        function () {
          try {
            testEl.doScroll('left')
          } catch (e) {
            return setTimeout(function() { ready(fn) }, 50)
          }
          fn()
        }()
    } :
    function (fn) {
      loaded ? fn() : fns.push(fn)
    })
})<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../../lib/oop");
var lang = require("../../lib/lang");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var TokenIterator = require("../../token_iterator").TokenIterator;

var FoldMode = exports.FoldMode = function(voidElements) {
    BaseFoldMode.call(this);
    this.voidElements = voidElements || {};
};
oop.inherits(FoldMode, BaseFoldMode);

(function() {

    this.getFoldWidget = function(session, foldStyle, row) {
        var tag = this._getFirstTagInLine(session, row);

        if (tag.closing)
            return foldStyle == "markbeginend" ? "end" : "";

        if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()])
            return "";

        if (tag.selfClosing)
            return "";

        if (tag.value.indexOf("/" + tag.tagName) !== -1)
            return "";

        return "start";
    };

    this._getFirstTagInLine = function(session, row) {
        var tokens = session.getTokens(row);
        var value = "";
        for (var i = 0; i < tokens.length; i++) {
            var token = tokens[i];
            if (token.type.indexOf("meta.tag") === 0)
                value += token.value;
            else
                value += lang.stringRepeat(" ", token.value.length);
        }

        return this._parseTag(value);
    };

    this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/;
    this._parseTag = function(tag) {

        var match = this.tagRe.exec(tag);
        var column = this.tagRe.lastIndex || 0;
        this.tagRe.lastIndex = 0;

        return {
            value: tag,
            match: match ? match[2] : "",
            closing: match ? !!match[3] : false,
            selfClosing: match ? !!match[5] || match[2] == "/>" : false,
            tagName: match ? match[4] : "",
            column: match[1] ? column + match[1].length : column
        };
    };

    /*
     * reads a full tag and places the iterator after the tag
     */
    this._readTagForward = function(iterator) {
        var token = iterator.getCurrentToken();
        if (!token)
            return null;

        var value = "";
        var start;

        do {
            if (token.type.indexOf("meta.tag") === 0) {
                if (!start) {
                    var start = {
                        row: iterator.getCurrentTokenRow(),
                        column: iterator.getCurrentTokenColumn()
                    };
                }
                value += token.value;
                if (value.indexOf(">") !== -1) {
                    var tag = this._parseTag(value);
                    tag.start = start;
                    tag.end = {
                        row: iterator.getCurrentTokenRow(),
                        column: iterator.getCurrentTokenColumn() + token.value.length
                    };
                    iterator.stepForward();
                    return tag;
                }
            }
        } while(token = iterator.stepForward());

        return null;
    };

    this._readTagBackward = function(iterator) {
        var token = iterator.getCurrentToken();
        if (!token)
            return null;

        var value = "";
        var end;

        do {
            if (token.type.indexOf("meta.tag") === 0) {
                if (!end) {
                    end = {
                        row: iterator.getCurrentTokenRow(),
                        column: iterator.getCurrentTokenColumn() + token.value.length
                    };
                }
                value = token.value + value;
                if (value.indexOf("<") !== -1) {
                    var tag = this._parseTag(value);
                    tag.end = end;
                    tag.start = {
                        row: iterator.getCurrentTokenRow(),
                        column: iterator.getCurrentTokenColumn()
                    };
                    iterator.stepBackward();
                    return tag;
                }
            }
        } while(token = iterator.stepBackward());

        return null;
    };

    this._pop = function(stack, tag) {
        while (stack.length) {

            var top = stack[stack.length-1];
            if (!tag || top.tagName == tag.tagName) {
                return stack.pop();
            }
            else if (this.voidElements[tag.tagName]) {
                return;
            }
            else if (this.voidElements[top.tagName]) {
                stack.pop();
                continue;
            } else {
                return null;
            }
        }
    };

    this.getFoldWidgetRange = function(session, foldStyle, row) {
        var firstTag = this._getFirstTagInLine(session, row);

        if (!firstTag.match)
            return null;

        var isBackward = firstTag.closing || firstTag.selfClosing;
        var stack = [];
        var tag;

        if (!isBackward) {
            var iterator = new TokenIterator(session, row, firstTag.column);
            var start = {
                row: row,
                column: firstTag.column + firstTag.tagName.length + 2
            };
            while (tag = this._readTagForward(iterator)) {
                if (tag.selfClosing) {
                    if (!stack.length) {
                        tag.start.column += tag.tagName.length + 2;
                        tag.end.column -= 2;
                        return Range.fromPoints(tag.start, tag.end);
                    } else
                        continue;
                }

                if (tag.closing) {
                    this._pop(stack, tag);
                    if (stack.length == 0)
                        return Range.fromPoints(start, tag.start);
                }
                else {
                    stack.push(tag)
                }
            }
        }
        else {
            var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length);
            var end = {
                row: row,
                column: firstTag.column
            };

            while (tag = this._readTagBackward(iterator)) {
                if (tag.selfClosing) {
                    if (!stack.length) {
                        tag.start.column += tag.tagName.length + 2;
                        tag.end.column -= 2;
                        return Range.fromPoints(tag.start, tag.end);
                    } else
                        continue;
                }

                if (!tag.closing) {
                    this._pop(stack, tag);
                    if (stack.length == 0) {
                        tag.start.column += tag.tagName.length + 2;
                        return Range.fromPoints(tag.start, end);
                    }
                }
                else {
                    stack.push(tag)
                }
            }
        }

    };

}).call(FoldMode.prototype);

});
<commit_msg>Addresses an issue where IE8 does not properly handle the RegExp in _parseTag, causing folding not to work for the XML mode (or modes that inherit XML). Tested XML mode in IE8/9 and major browsers. Should resolve ajaxorg/ace#1384<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../../lib/oop");
var lang = require("../../lib/lang");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var TokenIterator = require("../../token_iterator").TokenIterator;

var FoldMode = exports.FoldMode = function(voidElements) {
    BaseFoldMode.call(this);
    this.voidElements = voidElements || {};
};
oop.inherits(FoldMode, BaseFoldMode);

(function() {

    this.getFoldWidget = function(session, foldStyle, row) {
        var tag = this._getFirstTagInLine(session, row);

        if (tag.closing)
            return foldStyle == "markbeginend" ? "end" : "";

        if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()])
            return "";

        if (tag.selfClosing)
            return "";

        if (tag.value.indexOf("/" + tag.tagName) !== -1)
            return "";

        return "start";
    };

    this._getFirstTagInLine = function(session, row) {
        var tokens = session.getTokens(row);
        var value = "";
        for (var i = 0; i < tokens.length; i++) {
            var token = tokens[i];
            if (token.type.indexOf("meta.tag") === 0)
                value += token.value;
            else
                value += lang.stringRepeat(" ", token.value.length);
        }

        return this._parseTag(value);
    };

    this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/;
    this._parseTag = function(tag) {

        var match = tag.match(this.tagRe);
        var column = 0;

        return {
            value: tag,
            match: match ? match[2] : "",
            closing: match ? !!match[3] : false,
            selfClosing: match ? !!match[5] || match[2] == "/>" : false,
            tagName: match ? match[4] : "",
            column: match[1] ? column + match[1].length : column
        };
    };

    /*
     * reads a full tag and places the iterator after the tag
     */
    this._readTagForward = function(iterator) {
        var token = iterator.getCurrentToken();
        if (!token)
            return null;

        var value = "";
        var start;

        do {
            if (token.type.indexOf("meta.tag") === 0) {
                if (!start) {
                    var start = {
                        row: iterator.getCurrentTokenRow(),
                        column: iterator.getCurrentTokenColumn()
                    };
                }
                value += token.value;
                if (value.indexOf(">") !== -1) {
                    var tag = this._parseTag(value);
                    tag.start = start;
                    tag.end = {
                        row: iterator.getCurrentTokenRow(),
                        column: iterator.getCurrentTokenColumn() + token.value.length
                    };
                    iterator.stepForward();
                    return tag;
                }
            }
        } while(token = iterator.stepForward());

        return null;
    };

    this._readTagBackward = function(iterator) {
        var token = iterator.getCurrentToken();
        if (!token)
            return null;

        var value = "";
        var end;

        do {
            if (token.type.indexOf("meta.tag") === 0) {
                if (!end) {
                    end = {
                        row: iterator.getCurrentTokenRow(),
                        column: iterator.getCurrentTokenColumn() + token.value.length
                    };
                }
                value = token.value + value;
                if (value.indexOf("<") !== -1) {
                    var tag = this._parseTag(value);
                    tag.end = end;
                    tag.start = {
                        row: iterator.getCurrentTokenRow(),
                        column: iterator.getCurrentTokenColumn()
                    };
                    iterator.stepBackward();
                    return tag;
                }
            }
        } while(token = iterator.stepBackward());

        return null;
    };

    this._pop = function(stack, tag) {
        while (stack.length) {

            var top = stack[stack.length-1];
            if (!tag || top.tagName == tag.tagName) {
                return stack.pop();
            }
            else if (this.voidElements[tag.tagName]) {
                return;
            }
            else if (this.voidElements[top.tagName]) {
                stack.pop();
                continue;
            } else {
                return null;
            }
        }
    };

    this.getFoldWidgetRange = function(session, foldStyle, row) {
        var firstTag = this._getFirstTagInLine(session, row);

        if (!firstTag.match)
            return null;

        var isBackward = firstTag.closing || firstTag.selfClosing;
        var stack = [];
        var tag;

        if (!isBackward) {
            var iterator = new TokenIterator(session, row, firstTag.column);
            var start = {
                row: row,
                column: firstTag.column + firstTag.tagName.length + 2
            };
            while (tag = this._readTagForward(iterator)) {
                if (tag.selfClosing) {
                    if (!stack.length) {
                        tag.start.column += tag.tagName.length + 2;
                        tag.end.column -= 2;
                        return Range.fromPoints(tag.start, tag.end);
                    } else
                        continue;
                }

                if (tag.closing) {
                    this._pop(stack, tag);
                    if (stack.length == 0)
                        return Range.fromPoints(start, tag.start);
                }
                else {
                    stack.push(tag)
                }
            }
        }
        else {
            var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length);
            var end = {
                row: row,
                column: firstTag.column
            };

            while (tag = this._readTagBackward(iterator)) {
                if (tag.selfClosing) {
                    if (!stack.length) {
                        tag.start.column += tag.tagName.length + 2;
                        tag.end.column -= 2;
                        return Range.fromPoints(tag.start, tag.end);
                    } else
                        continue;
                }

                if (!tag.closing) {
                    this._pop(stack, tag);
                    if (stack.length == 0) {
                        tag.start.column += tag.tagName.length + 2;
                        return Range.fromPoints(tag.start, end);
                    }
                }
                else {
                    stack.push(tag)
                }
            }
        }

    };

}).call(FoldMode.prototype);

});
<|endoftext|>


<commit_before>/*global process */
var http = require('http');
var express = require('express');
var jsforceAjaxProxy = require('./proxy');

var app = express();

app.configure(function () {
  app.set('port', process.env.PORT || 3123);
});

app.configure('development', function () {
  app.use(express.errorHandler());
});

app.all('/proxy/?*', jsforceAjaxProxy({ enableCORS: true }));

app.get('/', function(req, res) {
  res.send('JSforce AJAX Proxy');
});

http.createServer(app).listen(app.get('port'), function () {
  console.log("Express server listening on port " + app.get('port'));
});
<commit_msg>update server to work in express 4<commit_after>/*global process */
var http = require('http');
var express = require('express');
var jsforceAjaxProxy = require('./proxy');

var app = express();

app.set('port', process.env.PORT || 3123);

if (process.env.NODE_ENV === 'development') {
  app.use(express.errorHandler());
}

app.all('/proxy/?*', jsforceAjaxProxy({ enableCORS: true }));

app.get('/', function(req, res) {
  res.send('JSforce AJAX Proxy');
});

http.createServer(app).listen(app.get('port'), function () {
  console.log("Express server listening on port " + app.get('port'));
});
<|endoftext|>


<commit_before>
var express = require("express");
var bodyParser = require("body-parser");
var cp = require('child_process');
var program = require('commander');
var moment = require('moment');

function collectRegistries(val, registryArgs) {
    registryArgs.push(val);
    return registryArgs;
}

program.version('0.0.1').usage('[options]').option('-r, --registries <registry>', 'Registry', collectRegistries, []).option('-l, --listen <n>', 'Listen on port', parseInt, 3000);
program.parse(process.argv);
var registries = program.registries;
console.log("Initialised with registries: ", registries);
var eppProcesses = {};
for (var accred in registries) {
    var registry = registries[accred];
    var eppProcess = cp.fork(__dirname + '/worker.js');
    eppProcess.send({
        "registry": registry
    });
    eppProcesses[registry] = eppProcess;
}
process.on('SIGINT', function() {
    var logoutResponse = function(data) {
        console.log("Got reply from logout: ", data);
    };
    for (var registry in eppProcesses) {
        var childProc = eppProcesses[registry];
        childProc.send({
            "command": "logout",
            "data": {}
        });
        childProc.on('message', logoutResponse);
    }
    process.exit(0);
});

var app = express();

app.use(bodyParser.json());

app.post('/command/:registry/:command', function(req, res) {
    var a = moment();
    if (! (req.params.registry in eppProcesses)) {
        res.send(400, {
            "error": "Unknown registry"
        });
        return;
    }
    var registry = req.params.registry;
    var childProc = eppProcesses[registry];
    var queryData = req.body;

    childProc.on('message', function(m) {
        var b = moment();
        var diff = b.diff(a, 'milliseconds');
        console.info('Request elapsed time: '+ diff.toString() + ' ms');
        res.end(m);
    });
    childProc.send({
        "command": req.params.command,
        "data": queryData
    });
});

app.listen(program.listen);

<commit_msg>try with "once" to make sure we don't get memory leak<commit_after>
var express = require("express");
var bodyParser = require("body-parser");
var cp = require('child_process');
var program = require('commander');
var moment = require('moment');

function collectRegistries(val, registryArgs) {
    registryArgs.push(val);
    return registryArgs;
}

program.version('0.0.1').usage('[options]').option('-r, --registries <registry>', 'Registry', collectRegistries, []).option('-l, --listen <n>', 'Listen on port', parseInt, 3000);
program.parse(process.argv);
var registries = program.registries;
console.log("Initialised with registries: ", registries);
var eppProcesses = {};
for (var accred in registries) {
    var registry = registries[accred];
    var eppProcess = cp.fork(__dirname + '/worker.js');
    eppProcess.send({
        "registry": registry
    });
    eppProcesses[registry] = eppProcess;
}
process.on('SIGINT', function() {
    var logoutResponse = function(data) {
        console.log("Got reply from logout: ", data);
    };
    for (var registry in eppProcesses) {
        var childProc = eppProcesses[registry];
        childProc.send({
            "command": "logout",
            "data": {}
        });
        childProc.once('message', logoutResponse);
    }
    process.exit(0);
});

var app = express();

app.use(bodyParser.json());

app.post('/command/:registry/:command', function(req, res) {
    var a = moment();
    if (! (req.params.registry in eppProcesses)) {
        res.send(400, {
            "error": "Unknown registry"
        });
        return;
    }
    var registry = req.params.registry;
    var childProc = eppProcesses[registry];
    var queryData = req.body;

    childProc.once('message', function(m) {
        var b = moment();
        var diff = b.diff(a, 'milliseconds');
        console.info('Request elapsed time: '+ diff.toString() + ' ms');
        res.end(m);
    });
    childProc.send({
        "command": req.params.command,
        "data": queryData
    });
});

app.listen(program.listen);

<|endoftext|>


<commit_before>var io = require('socket.io'),
    net = require('net'),
    cfg = require('./config'),
    ws = require('./web-server'),
    logger = require('./logger'),
    util = require('./util');

var STATIC_FOLDER = __dirname + '/../static/';

exports.start = function(configFilePath) {
  var config = cfg.parseConfig(configFilePath);

  logger.setLevel(config.logLevel);
  logger.useColors(config.logColors);

  var log = logger.create();
  var fileGuardian = new cfg.FileGuardian(config.files, config.autoWatch);
  log.info('Starting web server at http://localhost:' + config.port);
  var webServer = ws.createWebServer(fileGuardian, STATIC_FOLDER).listen(config.port);
  var socketServer = io.listen(webServer, {
    logger: logger.create('socket.io', 0),
    transports: ['websocket', 'xhr-polling', 'jsonp-polling']
  });

  // socket to captured browsers
  socketServer.sockets.on('connection', function (socket) {
    var browserName;
    var browserLog = log;
    log.debug('New browser has connected.');

    socket.on('result', function (result) {
//      browserLog.info('Test result id:', result.id);

      var LINE_LENGTH = 140;
      var PASSED = '\033[32mPASSED\033[39m';
      var FAILED = '\033[31mFAILED\033[39m';

      var msg = result.suite.join('.') + ' ' + result.description;
      // TODO(vojta): trim msg if too long...
      msg += new Array(LINE_LENGTH - msg.length - 6).join('.');
      msg += result.success ? PASSED : FAILED;

      console.log(msg);

      if (!result.success) {
        result.log.forEach(function(log) {
          console.log(util.formatError(log, '\t') + '\n');
        });
      }
    });

    socket.on('error', function(error) {
      browserLog.error(util.formatError(error, '\t'));
    });

    socket.on('complete', function() {
      // TODO(vojta)
    });

    socket.on('info', function(info) {
      browserLog.info(info);
    });

    socket.on('disconnect', function() {
      browserLog.warn('Disconnected');
    });

    socket.on('name', function(name) {
      browserName = util.browserFullNameToShort(name);
      browserLog = logger.create(browserName);
      browserLog.info('Connected and ready');
    });
  });

  fileGuardian.on('fileModified', function() {
    log.info('Execution (fired by autoWatch)');
    socketServer.sockets.emit('execute');
  });

  // listen on port, waiting for runner
  net.createServer(function (socket) {
    socket.on('data', function(buffer) {
      log.info('Execution (fired by runner)');
      fileGuardian.checkModifications();
      socketServer.sockets.emit('execute');
    });
  }).listen(config.runnerPort);
};
<commit_msg>Include browser name in test result<commit_after>var io = require('socket.io'),
    net = require('net'),
    cfg = require('./config'),
    ws = require('./web-server'),
    logger = require('./logger'),
    util = require('./util');

var STATIC_FOLDER = __dirname + '/../static/';

exports.start = function(configFilePath) {
  var config = cfg.parseConfig(configFilePath);

  logger.setLevel(config.logLevel);
  logger.useColors(config.logColors);

  var log = logger.create();
  var fileGuardian = new cfg.FileGuardian(config.files, config.autoWatch);
  log.info('Starting web server at http://localhost:' + config.port);
  var webServer = ws.createWebServer(fileGuardian, STATIC_FOLDER).listen(config.port);
  var socketServer = io.listen(webServer, {
    logger: logger.create('socket.io', 0),
    transports: ['websocket', 'xhr-polling', 'jsonp-polling']
  });

  // socket to captured browsers
  socketServer.sockets.on('connection', function (socket) {
    var browserName;
    var browserLog = log;
    log.debug('New browser has connected.');

    socket.on('result', function (result) {
      var LINE_LENGTH = 140;
      var PASSED = '\033[32mPASSED\033[39m';
      var FAILED = '\033[31mFAILED\033[39m';

      var msg = result.suite.join('.') + ' ' + result.description;

      // TODO(vojta): trim msg if too long...
      msg += new Array(LINE_LENGTH - browserName.length - 9 - msg.length - 6).join('.');
      msg += result.success ? PASSED : FAILED;
      browserLog.info(msg);

      if (!result.success) {
        result.log.forEach(function(log) {
          console.log(util.formatError(log, '\t') + '\n');
        });
      }
    });

    socket.on('error', function(error) {
      browserLog.error(util.formatError(error, '\t'));
    });

    socket.on('complete', function() {
      // TODO(vojta)
    });

    socket.on('info', function(info) {
      browserLog.info(info);
    });

    socket.on('disconnect', function() {
      browserLog.warn('Disconnected');
    });

    socket.on('name', function(name) {
      browserName = util.browserFullNameToShort(name);
      browserLog = logger.create(browserName);
      browserLog.info('Connected and ready');
    });
  });

  fileGuardian.on('fileModified', function() {
    log.info('Execution (fired by autoWatch)');
    socketServer.sockets.emit('execute');
  });

  // listen on port, waiting for runner
  net.createServer(function (socket) {
    socket.on('data', function(buffer) {
      log.info('Execution (fired by runner)');
      fileGuardian.checkModifications();
      socketServer.sockets.emit('execute');
    });
  }).listen(config.runnerPort);
};
<|endoftext|>


<commit_before>var Q = require('q'),
    QFS = require('q-fs'),
    QHTTP = require('q-http'),
    QS = require('querystring'),
    UTIL = require('util'),
    MIME = require('mime'),
    PATH = require('./path'),
    MAKE = require('./make'),
    LOGGER = require('./logger');

var defaultDocument = 'index.html';

exports.start = function(opts) {

    return rootExists(opts.root)()
        .then(showInfo(opts))
        .then(initBuildRunner(opts))
        .then(startServer(opts.root, opts.port, opts.hostname))
        .then(function(s) {
            return s.stopped;
        });

};

function showInfo(opts) {
    return function() {
        LOGGER.finfo("Project root is '%s'", opts.root);
        LOGGER.fverbose('Options are %j', opts);
    }
}

function rootExists(root) {

    return function() {
        return QFS.exists(root).then(function(exists) {
            if (!exists) return Q.reject(UTIL.format("Project root '%s' doesn't exist", root));
        });
    }

}

function startServer(root, port, hostname) {

    return function(runner) {
        var server = QHTTP.Server(requestHandler(root, runner));
        return server.listen(port, hostname).then(function() {
            LOGGER.finfo('Server is listening on port %s. Point your browser to http://localhost:%s/', port, port);
            return server;
        });
    }

}

function initBuildRunner(opts) {
    return function() {
        return Q.when(MAKE.createArch(opts.root), function(arch) {
            return new MAKE.APW(arch, opts.workers, {
                root: opts.root,
                verbose: opts.verbose,
                force: opts.force
            });
        })
    }
}

function requestHandler(root, runner) {

    return function(request, response) {

        var relPath = QS.unescape(request.path).replace(/^\/|\/$/g, ''),
            fullPath = PATH.join(root, relPath);

        LOGGER.fverbose('*** trying to access %s', fullPath);

        // try to find node in arch
        LOGGER.fverbose('*** searching for node "%s"', relPath);
        return runner.findNode(relPath)
            .fail(function(err) {
                if (typeof err === 'string') {
                    LOGGER.fverbose('*** node not found "%s"', relPath);
                    return;
                }
                return Q.reject(err);
            })
            .then(function(id) {
                if (!id) return;

                // found, run build
                LOGGER.fverbose('*** node found, building "%s"', id);
                return runner.process(id);
            })

            // not found or successfully build, try to find path on disk
            .then(processPath(response, fullPath))

            // any error, 500 internal server error
            .fail(httpError(response, 500));

    };

}

function processPath(response, path) {
    return function() {

        return QFS.exists(path).then(function(exists) {

            // 404 not found
            if (!exists) {
                return httpError(response, 404)(path);
            }

            // found, process file/directory
            return QFS.isDirectory(path).then(function(isDir) {

                if (isDir) {

                    // TODO: make defaultDocument buildable
                    var def = PATH.join(path, defaultDocument);
                    return QFS.isFile(def).then(function(isFile) {
                        if (isFile) return streamFile(response, def)();
                        return processDirectory(response, path)();
                    });

                }

                return streamFile(response, path)();

            });

        });

    }
}

function processDirectory(response, path) {
    return function() {
        return QFS.list(path).then(function(list) {
            response.status = 200;
            response.charset = 'utf8';
            response.headers = { 'content-type': 'text/html' };

            var body = response.body = [];

            pushFormatted(body,
                '<!DOCTYPE html><meta charset="utf-8"/><title>%s</title>' +
                    'Index of %s
',
            path);

            var files = [],
                dirs = ['..'],
                fillArrays = Q.all(list
                    .map(function(i) {
                        return QFS.isDirectory(PATH.join(path, i))
                            .then(function(isDir) {
                                (isDir ? dirs : files).push(i);
                            });
                    }));

            body.push(fillArrays.then(function() {
                var listing = [],
                    pushListing = function(objs, str) {
                        objs.sort();
                        objs.forEach(function(o) {
                            pushFormatted(listing, str, o, o);
                        });
                    };

                pushListing(dirs, '
/%s
');
                pushListing(files, '
%s
');

                return listing.join('');
            }));

            body.push('
');

            return response;
        });
    }
}

function streamFile(response, path) {
    return function() {

        response.status = 200;
        response.charset = 'binary';
        response.headers = { 'content-type': MIME.lookup(path) };
        response.body = QFS.open(path);

        return response;
    }
}

function httpError(response, code) {
    return function(err) {
        LOGGER.fwarn('*** HTTP error: %s, %s', code, (err && err.stack) || err);

        response.status = code;
        response.charset = 'utf8';
        response.headers = { 'content-type': 'text/html' };
        response.body = ['
HTTP error ' + code + '
'].concat(err? ['
', '' + (err.stack || err), '
'] : []);

        return response;
    }
}

function pushFormatted(arr, str) {
    arr.push(UTIL.format.apply(UTIL, Array.prototype.slice.call(arguments, 1)));
    return arr;
}
<commit_msg>Fix current directory output in bem server directory listing<commit_after>var Q = require('q'),
    QFS = require('q-fs'),
    QHTTP = require('q-http'),
    QS = require('querystring'),
    UTIL = require('util'),
    MIME = require('mime'),
    PATH = require('./path'),
    MAKE = require('./make'),
    LOGGER = require('./logger');

var defaultDocument = 'index.html';

exports.start = function(opts) {

    return rootExists(opts.root)()
        .then(showInfo(opts))
        .then(initBuildRunner(opts))
        .then(startServer(opts.root, opts.port, opts.hostname))
        .then(function(s) {
            return s.stopped;
        });

};

function showInfo(opts) {
    return function() {
        LOGGER.finfo("Project root is '%s'", opts.root);
        LOGGER.fverbose('Options are %j', opts);
    }
}

function rootExists(root) {

    return function() {
        return QFS.exists(root).then(function(exists) {
            if (!exists) return Q.reject(UTIL.format("Project root '%s' doesn't exist", root));
        });
    }

}

function startServer(root, port, hostname) {

    return function(runner) {
        var server = QHTTP.Server(requestHandler(root, runner));
        return server.listen(port, hostname).then(function() {
            LOGGER.finfo('Server is listening on port %s. Point your browser to http://localhost:%s/', port, port);
            return server;
        });
    }

}

function initBuildRunner(opts) {
    return function() {
        return Q.when(MAKE.createArch(opts.root), function(arch) {
            return new MAKE.APW(arch, opts.workers, {
                root: opts.root,
                verbose: opts.verbose,
                force: opts.force
            });
        })
    }
}

function requestHandler(root, runner) {

    return function(request, response) {

        var relPath = QS.unescape(request.path).replace(/^\/|\/$/g, ''),
            fullPath = PATH.join(root, relPath);

        LOGGER.fverbose('*** trying to access %s', fullPath);

        // try to find node in arch
        LOGGER.fverbose('*** searching for node "%s"', relPath);
        return runner.findNode(relPath)
            .fail(function(err) {
                if (typeof err === 'string') {
                    LOGGER.fverbose('*** node not found "%s"', relPath);
                    return;
                }
                return Q.reject(err);
            })
            .then(function(id) {
                if (!id) return;

                // found, run build
                LOGGER.fverbose('*** node found, building "%s"', id);
                return runner.process(id);
            })

            // not found or successfully build, try to find path on disk
            .then(processPath(response, fullPath))

            // any error, 500 internal server error
            .fail(httpError(response, 500));

    };

}

function processPath(response, path) {
    return function() {

        return QFS.exists(path).then(function(exists) {

            // 404 not found
            if (!exists) {
                return httpError(response, 404)(path);
            }

            // found, process file/directory
            return QFS.isDirectory(path).then(function(isDir) {

                if (isDir) {

                    // TODO: make defaultDocument buildable
                    var def = PATH.join(path, defaultDocument);
                    return QFS.isFile(def).then(function(isFile) {
                        if (isFile) return streamFile(response, def)();
                        return processDirectory(response, path)();
                    });

                }

                return streamFile(response, path)();

            });

        });

    }
}

function processDirectory(response, path) {
    return function() {
        return QFS.list(path).then(function(list) {
            response.status = 200;
            response.charset = 'utf8';
            response.headers = { 'content-type': 'text/html' };

            var body = response.body = [];

            pushFormatted(body,
                '<!DOCTYPE html><meta charset="utf-8"/><title>%s</title>' +
                    'Index of %s
',
            path, path);

            var files = [],
                dirs = ['..'],
                fillArrays = Q.all(list
                    .map(function(i) {
                        return QFS.isDirectory(PATH.join(path, i))
                            .then(function(isDir) {
                                (isDir ? dirs : files).push(i);
                            });
                    }));

            body.push(fillArrays.then(function() {
                var listing = [],
                    pushListing = function(objs, str) {
                        objs.sort();
                        objs.forEach(function(o) {
                            pushFormatted(listing, str, o, o);
                        });
                    };

                pushListing(dirs, '
/%s
');
                pushListing(files, '
%s
');

                return listing.join('');
            }));

            body.push('
');

            return response;
        });
    }
}

function streamFile(response, path) {
    return function() {

        response.status = 200;
        response.charset = 'binary';
        response.headers = { 'content-type': MIME.lookup(path) };
        response.body = QFS.open(path);

        return response;
    }
}

function httpError(response, code) {
    return function(err) {
        LOGGER.fwarn('*** HTTP error: %s, %s', code, (err && err.stack) || err);

        response.status = code;
        response.charset = 'utf8';
        response.headers = { 'content-type': 'text/html' };
        response.body = ['
HTTP error ' + code + '
'].concat(err? ['
', '' + (err.stack || err), '
'] : []);

        return response;
    }
}

function pushFormatted(arr, str) {
    arr.push(UTIL.format.apply(UTIL, Array.prototype.slice.call(arguments, 1)));
    return arr;
}
<|endoftext|>


<commit_before>/* jslint node: true, esnext: true */
"use strict";

const chokidar = require('chokidar');

const fs = require('fs');
const path = require("path");

const baseStep = require('kronos-step').step;
const LOG_LEVEL = require('kronos-step').log_level;
const messageFactory = require('kronos-step').message;

/**
 * Opens a read stream from a file from the file system
 */
class AdapterInboundFile extends baseStep {
	/**
	 * @param kronos The framework manager
	 * @param flow The flow this step was added to
	 * @param config The configration for this step
	 */
	constructor(kronos, flow, config) {
		super(kronos, flow, config);

		if (!config) {
			config = {};
		}

		// A regular expression. The file name must match this expression
		this.regEx = undefined;
		if (config.regEx) {
			this.regEx = new RegExp(config.regEx);
		}

		// an filter function. The function must have the signature
		// @param fileName The name of the file
		// function(fileName){}
		// If it returns a true vale the file will be read
		this.filter = undefined;
		if (config.filter) {
			if (typeof config.filter === 'function') {
				this.filter = config.filter;
			} else {
				throw 'Filter must be a function';
			}
		}

		// watch for changes on the directorys
		this.watchDir = undefined;
		if (config.watchDir) {
			this.watchDir = config.watchDir;
		}

		// if set to true, it will only file added new to the directory.
		// if false, it will start reading all the files in the directory
		this.onlyReadNewFiles = true;
		if (config.onlyReadNewFiles !== undefined) {
			this.onlyReadNewFiles = config.onlyReadNewFiles;
		}
	}

	/**
	 * Initializes the step
	 * Müsste eine promise zurück liefern. Aber für den test hier geht es auch so
	 */
	_start() {
		const self = this;
		if (self.watchDir) {
			let opt = {};
			if (self.onlyReadNewFiles) {
				opt.ignoreInitial = true;
			}

			self.watcher = chokidar.watch(self.watchDir, opt).on('add', function (filePath) {

				let absFileName = path.resolve(filePath);
				let fileDir = path.dirname(absFileName);
				let fileName = path.basename(absFileName);

				if (self.filter) {
					if (self.filter(fileName)) {
						self._createReadStreamMessage(absFileName, fileName, fileDir);
					}
				} else {
					if (self.regEx) {
						if (fileName.match(self.regEx)) {
							self._createReadStreamMessage(absFileName, fileName, fileDir);
						}
					} else {
						self._createReadStreamMessage(absFileName, fileName, fileDir);
					}
				}

			});
		}

	}

	_stop() {
		//	this.status = STATUS.stopping;
		if (this.watcher) {
			this.watcher.close();
		}
	}

	/**
	 * receives messages from incomming endpoints
	 */
	_doReceive(endpointName, message) {

		// This endpoint receives messages to read the given file
		if (endpointName === 'inFileTrigger') {
			if (message.payload) {
				if (typeof message.payload === 'string') {
					// take the payload as a single file name
					this._parseInboundFileMessage(undefined, message.payload, message);
				} else if (Array.isArray(message.payload)) {
					// take it as an array of file names
					for (let i = 0; i < message.payload.length; i++) {
						// iterate over the files
						this._parseInboundFileMessage(undefined, message.payload[i], message);
					}
				} else if (typeof message.payload === 'object') {
					if (message.payload.files) {
						let directory;
						if (message.payload.directory) {
							directory = message.payload.directory;
						}
						if (Array.isArray(message.payload.files)) {
							for (let i = 0; i < message.payload.files.length; i++) {
								// iterate over the files
								this._parseInboundFileMessage(directory, message.payload.files[i], message);
							}
						} {
							this._logMessage(LOG_LEVEL.error, message, "The 'files' property of the payload object mus be an array",
								'inFileTrigger');
						}
					}
					// take it as an array of strings
				} else {
					this._logMessage(LOG_LEVEL.error, message, "No matching payload in the message for this step", 'inFileTrigger');
				}
			} else {
				this._logMessage(LOG_LEVEL.error, message, "No payload in the message", 'inFileTrigger');
			}
		}
	}

	/**
	 * Checks the inbound file message.
	 * Does the files exists and converst the file names and directoryies
	 * in a way that the normal function could handle it
	 */
	_parseInboundFileMessage(directory, fileName, message) {
		let fileAbs;
		let fileDir;
		let fileRel;

		const self = this;

		if (path.isAbsolute(fileName)) {
			// The given file name is absolute
			fileAbs = fileName;
			fileDir = path.dirname(fileName);
			fileRel = path.basename(fileName);
		} else {
			// the file name is relative
			if (directory) {
				// build the absolute name
				fileDir = directory;
				fileRel = fileName;
				fileAbs = path.resolve(path.join(directory, fileName));
			} else {
				// error for relative file names the directory is needed
				self._logMessage(LOG_LEVEL.error, message, "For reative file names the directory is mandatory", 'inFileTrigger');
			}
		}

		if (fileAbs) {
			// check that the file exists
			fs.exists(fileAbs, function (exists) {
				if (exists) {
					// ok, trigger the file
					self._createReadStreamMessage(fileAbs, fileRel, fileDir, message);
				} else {
					// write error log
					self._logMessage(LOG_LEVEL.error, message, `The file '${fileAbs}' does not exists`, 'inFileTrigger');
				}
			});
		}

	}

	/**
	 * This method should be overwritten by the dreived class to setup the endpoints
	 * for this step.
	 */
	_setupEndpoints() {
		// The 'out' endpoint for this steps. This endpoint will emit file read stream requests
		this._addEndpointFromConfig({
			"name": "out",
			"active": true,
			"out": true
		});

		// This 'in' endpoint receives file read events. The payload in the message must have the following format:
		/*
		 * {
		 *  "directory" : dirname
		 *	"files" : [file1, .., fileN]
		 * }
		 * or {fileName}
		 * or [file1, .., fileN]
		 */
		this._addEndpointFromConfig({
			"name": "inFileTrigger",
			"passive": true,
			"in": true
		});
	}

	/**
	 * Opens the readFileStream and pushes the event to the next step
	 * @param absFileName The absolute file name.
	 * @param fileName The file name without the path
	 * @param directory The directory the file is in
	 * @param messageToClone If the file comes from an external trigger, some message informations
	 * needs to be copied from the trigger message.
	 */
	_createReadStreamMessage(absFileName, fileName, directory, messageToClone) {
		const self = this;
		let stream = fs.createReadStream(absFileName);
		if (stream) {

			const message = messageFactory({
				"file_name": fileName,
				"directory": directory
			}, messageToClone);

			message.payload = stream;
			// Get the file stats as sdditional information on the request
			fs.stat(absFileName, function (stats) {
				message.header.file_stat = stats;
				self._push("out", message);
			});
		}
	}

}

module.exports = function (kronos, flow, opts) {
	return new AdapterInboundFile(kronos, flow, opts);
};
<commit_msg>feat: make travis run 3<commit_after>/* jslint node: true, esnext: true */
"use strict";

const chokidar = require('chokidar');

const fs = require('fs');
const path = require("path");

const baseStep = require('kronos-step').step;
const LOG_LEVEL = require('kronos-step').log_level;
const messageFactory = require('kronos-step').message;

/**
 * Opens a read stream from a file from the file system
 */
class AdapterInboundFile extends baseStep {
	/**
	 * @param kronos The framework manager
	 * @param flow The flow this step was added to
	 * @param config The configration for this step
	 */
	constructor(kronos, flow, config) {
		super(kronos, flow, config);

		if (!config) {
			config = {};
		}

		// A regular expression. The file name must match this expression
		this.regEx = undefined;
		if (config.regEx) {
			this.regEx = new RegExp(config.regEx);
		}

		// an filter function. The function must have the signature
		// @param fileName The name of the file
		// function(fileName){}
		// If it returns a true vale the file will be read
		this.filter = undefined;
		if (config.filter) {
			if (typeof config.filter === 'function') {
				this.filter = config.filter;
			} else {
				throw 'Filter must be a function';
			}
		}

		// watch for changes on the directorys
		this.watchDir = undefined;
		if (config.watchDir) {
			this.watchDir = config.watchDir;
		}

		// if set to true, it will only file added new to the directory.
		// if false, it will start reading all the files in the directory
		this.onlyReadNewFiles = true;
		if (config.onlyReadNewFiles !== undefined) {
			this.onlyReadNewFiles = config.onlyReadNewFiles;
		}
	}

	/**
	 * Initializes the step
	 * Müsste eine promise zurück liefern. Aber für den test hier geht es auch so
	 */
	_start() {
		const self = this;
		if (self.watchDir) {
			let opt = {};
			if (self.onlyReadNewFiles) {
				opt.ignoreInitial = true;
			}

			self.watcher = chokidar.watch(self.watchDir, opt).on('add', function (filePath) {

				let absFileName = path.resolve(filePath);
				let fileDir = path.dirname(absFileName);
				let fileName = path.basename(absFileName);

				if (self.filter) {
					if (self.filter(fileName)) {
						self._createReadStreamMessage(absFileName, fileName, fileDir);
					}
				} else {
					if (self.regEx) {
						if (fileName.match(self.regEx)) {
							self._createReadStreamMessage(absFileName, fileName, fileDir);
						}
					} else {
						self._createReadStreamMessage(absFileName, fileName, fileDir);
					}
				}

			});
		}

	}

	_stop() {
		//	this.status = STATUS.stopping;
		if (this.watcher) {
			this.watcher.close();
		}
	}

	/**
	 * receives messages from incomming endpoints
	 */
	_doReceive(endpointName, message) {

		// This endpoint receives messages to read the given file
		if (endpointName === 'inFileTrigger') {
			if (message.payload) {
				if (typeof message.payload === 'string') {
					// take the payload as a single file name
					this._parseInboundFileMessage(undefined, message.payload, message);
				} else if (Array.isArray(message.payload)) {
					// take it as an array of file names
					for (let i = 0; i < message.payload.length; i++) {
						// iterate over the files
						this._parseInboundFileMessage(undefined, message.payload[i], message);
					}
				} else if (typeof message.payload === 'object') {
					if (message.payload.files) {
						let directory;
						if (message.payload.directory) {
							directory = message.payload.directory;
						}
						if (Array.isArray(message.payload.files)) {
							for (let i = 0; i < message.payload.files.length; i++) {
								// iterate over the files
								this._parseInboundFileMessage(directory, message.payload.files[i], message);
							}
						} {
							this._logMessage(LOG_LEVEL.error, message, "The 'files' property of the payload object mus be an array",
								'inFileTrigger');
						}
					}
					// take it as an array of strings
				} else {
					this._logMessage(LOG_LEVEL.error, message, "No matching payload in the message for this step", 'inFileTrigger');
				}
			} else {
				this._logMessage(LOG_LEVEL.error, message, "No payload in the message", 'inFileTrigger');
			}
		}
	}

	/**
	 * Checks the inbound file message.
	 * Does the files exists and converst the file names and directoryies
	 * in a way that the normal function could handle it
	 */
	_parseInboundFileMessage(directory, fileName, message) {
		let fileAbs;
		let fileDir;
		let fileRel;

		const self = this;

		if (path.isAbsolute(fileName)) {
			// The given file name is absolute
			fileAbs = fileName;
			fileDir = path.dirname(fileName);
			fileRel = path.basename(fileName);
		} else {
			// the file name is relative
			if (directory) {
				// build the absolute name
				fileDir = directory;
				fileRel = fileName;
				fileAbs = path.resolve(path.join(directory, fileName));
			} else {
				// error for relative file names the directory is needed
				self._logMessage(LOG_LEVEL.error, message, "For reative file names the directory is mandatory", 'inFileTrigger');
			}
		}

		if (fileAbs) {
			// check that the file exists
			fs.exists(fileAbs, function (exists) {
				if (exists) {
					// ok, trigger the file
					self._createReadStreamMessage(fileAbs, fileRel, fileDir, message);
				} else {
					// write error log
					self._logMessage(LOG_LEVEL.error, message, `The file '${fileAbs}' does not exists`, 'inFileTrigger');
				}
			});
		}

	}

	/**
	 * This method should be overwritten by the dreived class to setup the endpoints
	 * for this step.
	 */
	_setupEndpoints() {
		// The 'out' endpoint for this steps. This endpoint will emit file read stream requests
		this._addEndpointFromConfig({
			"name": "out",
			"active": true,
			"out": true
		});

		// This 'in' endpoint receives file read events. The payload in the message must have the following format:
		/*
		 * {
		 *  "directory" : dirname
		 *	"files" : [file1, .., fileN]
		 * }
		 * or {fileName}
		 * or [file1, .., fileN]
		 */
		this._addEndpointFromConfig({
			"name": "inFileTrigger",
			"passive": true,
			"in": true
		});
	}

	/**
	 * Opens the readFileStream and pushes the event to the next step
	 * @param absFileName The absolute file name.
	 * @param fileName The file name without the path
	 * @param directory The directory the file is in
	 * @param messageToClone If the file comes from an external trigger, some message informations
	 * needs to be copied from the trigger message.
	 */
	_createReadStreamMessage(absFileName, fileName, directory, messageToClone) {
		const self = this;
		let stream = fs.createReadStream(absFileName);
		if (stream) {

			const message = messageFactory({
				"file_name": fileName,
				"directory": directory
			}, messageToClone);

			message.payload = stream;
			// Get the file stats as sdditional information on the request
			fs.stat(absFileName, function (stats) {
				message.header.file_stat = stats;
				self._push("out", message);
			});
		}
	}

}

module.exports = function (kronos, flow, opts) {
	return new AdapterInboundFile(kronos, flow, opts);
};
<|endoftext|>


<commit_before>var connections = {};

// Override in application so meteor-presence can handle multiple servers
Presences.serverId = '';

var expire = function(id) {
  Presences.remove(id);
  delete connections[id];
};

var tick = function(id) {
  connections[id].lastSeen = Date.now();
};

Meteor.startup(function() {
  if (!Presences.serverId) {
    Presences.remove({serverId: {$exists: false}});
  } else {
    Presences.remove({serverId: Presences.serverId});
  }
});

Meteor.onConnection(function(connection) {
  // console.log('connectionId: ' + connection.id);
  var presence = { _id: connection.id };
  if (Presences.serverId) {
    presence.serverId = Presences.serverId;
  }
  Presences.insert(presence);

  connections[connection.id] = {};
  tick(connection.id);

  connection.onClose(function() {
    // console.log('connection closed: ' + connection.id);
    expire(connection.id);
  });
});

Meteor.methods({
  presenceTick: function() {
    check(arguments, [Match.Any]);
    if (this.connection && connections[this.connection.id])
      tick(this.connection.id);
  }
});

Meteor.setInterval(function() {
  _.each(connections, function(connection, id) {
    if (connection.lastSeen < (Date.now() - 10000))
      expire(id);
  });
}, 5000);
<commit_msg>Multi server support - clearing up<commit_after>var connections = {};
var servers = new Mongo.Collection('presenceServers');

// Override in application so meteor-presence can handle multiple servers
Presences.serverId = '';

var expire = function(id) {
  Presences.remove(id);
  delete connections[id];
};

var tick = function(id) {
  connections[id].lastSeen = Date.now();
};

var serverTick = function() {
  if (!Presences.serverId) return;
  servers.upsert({_id: Presences.serverId}, {$set: {tick: Date.now()}});
}

Meteor.startup(function() {
  if (!Presences.serverId) {
    Presences.remove({serverId: {$exists: false}});
  } else {
    Presences.remove({serverId: Presences.serverId});
    serverTick();
  }
});

Meteor.onConnection(function(connection) {
  // console.log('connectionId: ' + connection.id);
  var presence = { _id: connection.id };
  if (Presences.serverId) {
    presence.serverId = Presences.serverId;
  }
  Presences.insert(presence);

  connections[connection.id] = {};
  tick(connection.id);

  connection.onClose(function() {
    // console.log('connection closed: ' + connection.id);
    expire(connection.id);
  });
});

Meteor.methods({
  presenceTick: function() {
    check(arguments, [Match.Any]);
    if (this.connection && connections[this.connection.id])
      tick(this.connection.id);
  }
});

Meteor.setInterval(function() {
  _.each(connections, function(connection, id) {
    if (connection.lastSeen < (Date.now() - 10000))
      expire(id);
  });
}, 5000);

Meteor.setInterval(function() {
  serverTick();
}, 60000);

Meteor.setInterval(function() {
  servers.remove({tick: {$lt: Date.now() - 60000}});
  var serverIds = servers.find({}, {fields: {_id: 1}}).map(function(s) {return s._id});
  Presences.remove({serverId: {$nin: serverIds}});
}, 180000);<|endoftext|>