<commit_before>const express = require('express');
const https = require('https');
const http = require('http');
const fs = require('fs');
const url = require('url');
const app = express();
const pages = require('./pages');
const mongoose = require('mongoose');
const redis = require("redis");
const redislock = require("redis-lock");

var maowtm = function (config) {
    config = config || {};
    this.config = config;
    this._mongodb = config.db || "mongodb://127.0.0.1";
    mongoose.connect(this._mongodb);
    this.db = mongoose.connection;
    this._redis = config.redis || "127.0.0.1";
    this.redis = redis.createClient({
        host: this._redis
    });
    this.lock = redislock(this.redis);
    this._listen = config.listen || "127.0.0.1";
    if (typeof this._listen == 'array') {
        if (this._listen.length > 2) {
            throw new Error("Can't listen more than 2.");
        }
        this._listen2 = this._listen[1];
        this._listen = this._listen[0];
    }
    this._ssl = config.ssl;
    if (!(this._ssl && this._ssl.cert && this._ssl.key))
        throw new Error("No ssl cert provided")
    var _this = this;

    this.db.on('error', function (err) {
        console.error(err);
        console.error('Faild to connect to db. Exiting...');
        process.exit(1);
    });
    this.db.on('open', function() {

        try {
            fs.accessSync('acme-challenge', fs.R_OK);
            console.log('ACME challenge file read.');
            var ct = fs.readFileSync('acme-challenge', {encoding: 'utf8'});
            app.get('/.well-known/acme-challenge/*', function (req, res) {
                res.send(ct);
            });
        } catch (e) {
        }

        app.use(function(req, res, next) {
            if(!req.secure) {
                res.redirect(302, 'https://' + req.hostname + req.originalUrl);
            } else {
                res.set('Strict-Transport-Security', 'max-age=10886400; includeSubdomains; preload');
                res.set('X-XSS-Protection', '1; mode=block');
                res.set('X-Frame-Options', 'sameorigin');
                res.set('X-Content-Type-Options', 'nosniff');
                next();
            }
        });

        app.use(function(req, res, next) {
            res.error = function (status, error) {
                if (typeof status != 'number') {
                    error = status;
                    status = 501;
                }
                res.status(status);
                res.send(pages.error({error: error, status: status, req: req}));
            };
            next();
        });

        app.use(require('./subs/static').setLock(_this.lock));

        // Add trailing / for all GET for all router below. ( i.e. Not including static )
        app.use(function(req, res, next) {
            var prasedUrl = url.parse(req.originalUrl, false);
            if(req.method == 'GET' && prasedUrl.pathname.substr(-1) != '/') {
                prasedUrl.pathname += '/';
                res.redirect(302, url.format(prasedUrl));
            } else {
                next();
            }
        });

        app.use(require('./subs/main'));

        app.use(function(req, res) {
            res.error(404, "Not find");
        });

        var image = mongoose.model('image');
        var imgs = fs.readdirSync('static/imgs');
        var doAddActivities;
        var activityFiles;
        var actcd = __dirname + '/data/activities';
        function doAddImg(i) {
            if (i >= imgs.length) {
                fs.readdir(actcd, function (err, files) {
                    if(err) {
                        console.error(err);
                        process.exit(1);
                    } else {
                        activityFiles = files;
                        doAddActivities(0);
                    }
                });
            } else {
                image.addImageIfNotExist(imgs[i], __dirname + '/static/imgs/' + imgs[i], function (err) {
                    if(err) {
                        console.error(err);
                        console.error('Faild to load image: ' + imgs[i].name);
                        process.exit(1);
                    } else {
                        doAddImg(i + 1);
                    }
                });
            }
        }
        var activityImportLog = mongoose.model('activityImportLog');
        doAddActivities = function (i) {
            if(i >= activityFiles.length) {
                http.createServer(app).listen(80, _this._listen);
                const httpsopts = {
                    key: fs.readFileSync(_this._ssl.key),
                    cert: fs.readFileSync(_this._ssl.cert),
                    ciphers: "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:ECDHE-ECDSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA",
                    honorCipherOrder: true
                };
                https.createServer(httpsopts, app).listen(443, _this._listen);
                if(_this._listen2) {
                    http.createServer(app).listen(80, _this._listen2);
                    https.createServer(httpsopts, app).listen(443, _this._listen2);
                }
                return;
            }
            var fname = activityFiles[i];
            if(!fname.match(/^[a-zA-Z0-9]+\.json$/)) {
                doAddActivities(i + 1);
                return;
            }
            activityImportLog.importFile(fname, function (err) {
                if(err) {
                    console.error(err);
                    console.error('Faild to import ' + activityFiles[i] + ' .');
                    process.exit(1);
                } else {
                    doAddActivities(i + 1);
                }
            }, actcd);
        }
        doAddImg(0);
    });
};

module.exports = maowtm;

<commit_msg>typeof [] == "object"<commit_after>const express = require('express');
const https = require('https');
const http = require('http');
const fs = require('fs');
const url = require('url');
const app = express();
const pages = require('./pages');
const mongoose = require('mongoose');
const redis = require("redis");
const redislock = require("redis-lock");

var maowtm = function (config) {
    config = config || {};
    this.config = config;
    this._mongodb = config.db || "mongodb://127.0.0.1";
    mongoose.connect(this._mongodb);
    this.db = mongoose.connection;
    this._redis = config.redis || "127.0.0.1";
    this.redis = redis.createClient({
        host: this._redis
    });
    this.lock = redislock(this.redis);
    this._listen = config.listen || "127.0.0.1";
    if (typeof this._listen == 'object') {
        if (this._listen.length > 2) {
            throw new Error("Can't listen more than 2.");
        }
        this._listen2 = this._listen[1];
        this._listen = this._listen[0];
    }
    this._ssl = config.ssl;
    if (!(this._ssl && this._ssl.cert && this._ssl.key))
        throw new Error("No ssl cert provided")
    var _this = this;

    this.db.on('error', function (err) {
        console.error(err);
        console.error('Faild to connect to db. Exiting...');
        process.exit(1);
    });
    this.db.on('open', function() {

        try {
            fs.accessSync('acme-challenge', fs.R_OK);
            console.log('ACME challenge file read.');
            var ct = fs.readFileSync('acme-challenge', {encoding: 'utf8'});
            app.get('/.well-known/acme-challenge/*', function (req, res) {
                res.send(ct);
            });
        } catch (e) {
        }

        app.use(function(req, res, next) {
            if(!req.secure) {
                res.redirect(302, 'https://' + req.hostname + req.originalUrl);
            } else {
                res.set('Strict-Transport-Security', 'max-age=10886400; includeSubdomains; preload');
                res.set('X-XSS-Protection', '1; mode=block');
                res.set('X-Frame-Options', 'sameorigin');
                res.set('X-Content-Type-Options', 'nosniff');
                next();
            }
        });

        app.use(function(req, res, next) {
            res.error = function (status, error) {
                if (typeof status != 'number') {
                    error = status;
                    status = 501;
                }
                res.status(status);
                res.send(pages.error({error: error, status: status, req: req}));
            };
            next();
        });

        app.use(require('./subs/static').setLock(_this.lock));

        // Add trailing / for all GET for all router below. ( i.e. Not including static )
        app.use(function(req, res, next) {
            var prasedUrl = url.parse(req.originalUrl, false);
            if(req.method == 'GET' && prasedUrl.pathname.substr(-1) != '/') {
                prasedUrl.pathname += '/';
                res.redirect(302, url.format(prasedUrl));
            } else {
                next();
            }
        });

        app.use(require('./subs/main'));

        app.use(function(req, res) {
            res.error(404, "Not find");
        });

        var image = mongoose.model('image');
        var imgs = fs.readdirSync('static/imgs');
        var doAddActivities;
        var activityFiles;
        var actcd = __dirname + '/data/activities';
        function doAddImg(i) {
            if (i >= imgs.length) {
                fs.readdir(actcd, function (err, files) {
                    if(err) {
                        console.error(err);
                        process.exit(1);
                    } else {
                        activityFiles = files;
                        doAddActivities(0);
                    }
                });
            } else {
                image.addImageIfNotExist(imgs[i], __dirname + '/static/imgs/' + imgs[i], function (err) {
                    if(err) {
                        console.error(err);
                        console.error('Faild to load image: ' + imgs[i].name);
                        process.exit(1);
                    } else {
                        doAddImg(i + 1);
                    }
                });
            }
        }
        var activityImportLog = mongoose.model('activityImportLog');
        doAddActivities = function (i) {
            if(i >= activityFiles.length) {
                http.createServer(app).listen(80, _this._listen);
                const httpsopts = {
                    key: fs.readFileSync(_this._ssl.key),
                    cert: fs.readFileSync(_this._ssl.cert),
                    ciphers: "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:ECDHE-ECDSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA",
                    honorCipherOrder: true
                };
                https.createServer(httpsopts, app).listen(443, _this._listen);
                if(_this._listen2) {
                    http.createServer(app).listen(80, _this._listen2);
                    https.createServer(httpsopts, app).listen(443, _this._listen2);
                }
                return;
            }
            var fname = activityFiles[i];
            if(!fname.match(/^[a-zA-Z0-9]+\.json$/)) {
                doAddActivities(i + 1);
                return;
            }
            activityImportLog.importFile(fname, function (err) {
                if(err) {
                    console.error(err);
                    console.error('Faild to import ' + activityFiles[i] + ' .');
                    process.exit(1);
                } else {
                    doAddActivities(i + 1);
                }
            }, actcd);
        }
        doAddImg(0);
    });
};

module.exports = maowtm;

<|endoftext|>


<commit_before>var blessed = require('blessed')
	, contrib = require('blessed-contrib')
	, Server = require('ssh2').Server;

var config = { privateKey: require('fs').readFileSync('keys/host_rsa.key'),};

function noop(v) {}

var ssh = new Server(config, function(client){
  var stream,
      name;

  client.on('authentication', function(ctx){
    return ctx.accept();
  });

  client.on('ready', function(ctx){
    var rows,
        columns,
        term;

    client.once('session', function(accept, reject){
      var session = accept();

      session.once('pty', function(accept, reject, info){
          rows = info.rows;
          cols = info.cols;
          term = info.term;
          accept && accept();
      });

      session.on('window-change', function(accept, reject, info) {
        rows = info.rows;
        cols = info.cols;
        if (stream) {
          stream.rows = rows;
          stream.columns = cols;
          stream.emit('resize');
        }
        accept && accept();
      });

      session.once('shell', function(accept, reject){
        // accept() returns a Channel for the interactive shell.
        stream = accept();

        // https://github.com/mscdex/ssh2/#pseudo-tty-settings
        stream.name = name;
        stream.rows = rows || 24;
        stream.columns = cols || 80;
        stream.isTTY = true;
        stream.setRawMode = noop;
        stream.on('error', noop);

        var screen = new blessed.screen({
          autoPadding: true,
          smartCSR: true,
          program: new blessed.program({
            input: stream,
            output: stream
          }),
          terminal: term || 'ansi'
        });

        var grid = new contrib.grid({rows: 12, cols: 12, screen: screen})

        screen.title = 'Welcome to #!';
        var map = grid.set(0, 0, 4, 4, contrib.map, {label: 'World Map'})
        var box = grid.set(4, 4, 4, 4, blessed.box, {content: 'My Box'})

        screen.key(['escape', 'q', 'C-c'], function(ch, key) {
          stream.end();
        });

        screen.render();
      }); //shell
    }); // session
  }); //ready

  client.on('end', function(){
    console.log("Client disconnected");
  });

  client.on('error', function(err){
    // what's an error?
  });

});

ssh.listen(4444, function(){
  console.log('Listening on port ' + this.address().port);
});
<commit_msg>added welcome screen<commit_after>var blessed = require('blessed')
	, contrib = require('blessed-contrib')
	, Server = require('ssh2').Server;

var config = { privateKey: require('fs').readFileSync('keys/host_rsa.key'),};

function noop(v) {}

var ssh = new Server(config, function(client){
  var stream,
      name;

  client.on('authentication', function(ctx){
    return ctx.accept();
  });

  client.on('ready', function(ctx){
    var rows,
        columns,
        term;

    client.once('session', function(accept, reject){
      var session = accept();

      session.once('pty', function(accept, reject, info){
          rows = info.rows;
          cols = info.cols;
          term = info.term;
          accept && accept();
      });

      session.on('window-change', function(accept, reject, info) {
        rows = info.rows;
        cols = info.cols;
        if (stream) {
          stream.rows = rows;
          stream.columns = cols;
          stream.emit('resize');
        }
        accept && accept();
      });

      session.once('shell', function(accept, reject){
        // accept() returns a Channel for the interactive shell.
        stream = accept();

        // https://github.com/mscdex/ssh2/#pseudo-tty-settings
        stream.name = name;
        stream.rows = rows || 24;
        stream.columns = cols || 80;
        stream.isTTY = true;
        stream.setRawMode = noop;
        stream.on('error', noop);

        var screen1 = new blessed.screen({
          autoPadding: true,
          smartCSR: true,
          program: new blessed.program({
            input: stream,
            output: stream
          }),
		  dockBorders: true,
          terminal: term || 'ansi'
        });

        var grid = new contrib.grid({rows: 12, cols: 12, hideBorder: true, screen: screen1})

        screen1.title = 'Welcome to #!';
		var welcomeText = 'Welcome to #!. This network has three rules:\r\n\r\n1. When people need help, teach. Don\'t do it for them\r\n2. Don\'t use our resources for closed source projects\r\n3. Be excellent to each other\r\n \r\nWe are a diverse community of people who love teaching and learning.Putting a #! at the beginning of a \"script\" style program tells a computer that it needs to \"do something\" or \"execute\" this file. Likewise, we are a community of people that like to \"do stuff\".\r\n\r\nIf you like technology, and you want to learn to write your first program, learn to use Linux, or even take on interesting challenges with some of the best in the industry, you are in the right place.\r\n \r\nThe following will set you up with a \"shell\" account on one of our shared systems. From here you can run IRC chat clients to talk to us,\r\n access to personal file storage and web hosting, and a wide range of development tools. \r\n \r\nEverything should work perfectly, unless it doesn\'t\r\n \r\nPlease report any issues here: \r\n-> https:\/\/github.com\/hashbang\/hashbang.sh\/issues\/\r\n'
        var logo = grid.set(1, 1, 8, 8, blessed.box, { content: '    _  _     _ \r\n  _| || |_  | |\r\n |_  __  _| | |\r\n  _| || |_  | |\r\n |_  __  _| |_|\r\n   |_||_|   (_)\r\n' })
        var box = grid.set(1, 3, 8, 8, blessed.box, { content: welcomeText, scrollable: true, alwaysScroll: true, keys: true, vi: true, scrollbar: { ch: ' ', inverse: true } })
		var boxconfirm = grid.set(8, 1, 2, 10, blessed.text, { content: blessed.parseTags("{bold}Press 'Y' to continue or press 'Q' to quit.{/bold}"),  style: { bg: 'black', fg: 'green'}, padding: 2})

		box.focus();

        screen1.key(['escape', 'q', 'C-c'], function(ch, key) {
          stream.end();
        });

        screen1.key(['y', 'Y'], function(ch, key) {
          console.log('User pressed' + key);
        });

        screen1.render();
      }); //shell
    }); // session
  }); //ready

  client.on('end', function(){
    console.log("Client disconnected");
  });

  client.on('error', function(err){
    // what's an error?
  });

});

ssh.listen(4444, function(){
  console.log('Listening on port ' + this.address().port);
});
<|endoftext|>


<commit_before>var supportsPushState = !!history.pushState

function Router(){
  var router = this
  router.routeMap = {}
  if (window.addEventListener){
    window.addEventListener('popstate', function(){
      router.goto(location.pathname)
    })
  }
}

Router.prototype = {
  get: function(pattern, handler){
    this.routeMap[pattern] = handler
  },
  goto: function(path){
    if (path !== location.pathname){
      if (supportsPushState){
        history.pushState({}, '', path)
      }else{
        window.location = path
        return
      }
    }
    for (var pattern in this.routeMap){
      var params
      if (params = this._match(pattern, path)){
        this.routeMap[pattern](params)
        break
      }
    }
  },
  captureAnchorTagClicks: function(){
    document.addEventListener('click', function(event) {
      var element = e.target,
        href, target, isAnchor, isRelative, isLocal;

      if (element && element.nodeName == 'A') {
        href = element.attributes.href && element.attributes.href.textContent;
        target = element.attributes.target && element.attributes.target.textContent;
        isAnchor = href.indexOf('#') === 0;
        isRelative = href.indexOf('http') !== 0;
        isLocal = href.indexOf(location.origin) === 0;

        if (target !== '_blank' && (isRelative || isLocal) && !isAnchor) {
          // don't change page, use push state, return false for browsers with no preventDefault
          if (e.preventDefault) {
            e.preventDefault();
          }
          history.pushState({}, '', href);
          return false;
        }
      }
    });
  },
  start: function(){
    this.goto(location.pathname);
  },
  _match: function(pattern, url){
    var varnames = pattern.match(/(:[a-zA-Z0-9]+)/g)
    var re = new RegExp('^' + pattern.replace(/(:[a-zA-Z0-9]+)/g,
      '([a-zA-Z0-9]+)') + '$')
    var match = url.match(re)
    if (!match) return null
    var params = {}
    for (var i = 1; i < match.length; i++){
      var varname = varnames[i - 1].substring(1)
      params[varname] = match[i]
    }
    return params
  }
}

module.exports = Router<commit_msg>jslint style cleanup<commit_after>var supportsPushState = !! history.pushState;

function Router() {
    var router = this;

    router.routeMap = {};

    if (window.addEventListener) {
        window.addEventListener('popstate', function() {
            router.goto(location.pathname);
        });
    }
}

Router.prototype = {

    get: function(pattern, handler) {
        this.routeMap[pattern] = handler
    },

    goto: function(path) {
        var params, pattern;

        if (path !== location.pathname) {
            if (supportsPushState) {
                history.pushState({}, '', path);
            } else {
                window.location = path;
                return;
            }
        }
        for (pattern in this.routeMap) {
            if (params = this._match(pattern, path)) {
                this.routeMap[pattern](params);
                break;
            }
        }
    },

    captureAnchorTagClicks: function() {
        document.addEventListener('click', function(event) {
            var element = e.target,
                href, target, isAnchor, isRelative, isLocal;

            if (element && element.nodeName == 'A') {
                href = element.attributes.href && element.attributes.href.textContent;
                target = element.attributes.target && element.attributes.target.textContent;
                isAnchor = href.indexOf('#') === 0;
                isRelative = href.indexOf('http') !== 0;
                isLocal = href.indexOf(location.origin) === 0;

                if (target !== '_blank' && (isRelative || isLocal) && !isAnchor) {
                    // don't change page, use push state, return false for browsers with no preventDefault
                    if (e.preventDefault) {
                        e.preventDefault();
                    }
                    history.pushState({}, '', href);
                    return false;
                }
            }
        });
    },

    start: function() {
        this.goto(location.pathname);
    },

    _match: function(pattern, url) {
        var varnames = pattern.match(/(:[a-zA-Z0-9]+)/g),
            re = new RegExp('^' + pattern.replace(/(:[a-zA-Z0-9]+)/g,
                '([a-zA-Z0-9]+)') + '$'),
            match = url.match(re),
            params = {},
            i = 1,
            varname;

        if (!match) {
            return null;
        }

        for (i = 1; i < match.length; i++) {
            varname = varnames[i - 1].substring(1)
            params[varname] = match[i]
        }

        return params
    }
}

module.exports = Router
<|endoftext|>


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

require('colors');
var program = require('commander');
var promise = require('promise');
var spawn = require('child_process').spawn;
var pkg = require('./package.json');
var CWD = process.cwd();

var startDate = new Date();

program.version(pkg.version)
	.option('-t, --time <n>', 'seconds between two commits', parseFloat)
	.option('-p, --push <n>', 'push to specified remote after commit')
	.option('-b, --branch <n>', 'name of the branch to push')
	.parse(process.argv);

function run(command, args) {
  return new Promise(function(resolve, reject) {
    var task = spawn(command, args, {
    	cwd: CWD
    });
    task.on('close', function(code) {
      if (code !== 0) reject(new Error(command + ' process exited with code ' + code));
      else resolve();
    });
    task.stdout.pipe(process.stdout);
    task.stderr.pipe(process.stderr);
  });
}

function addAll() {
	return run('git', ['add', '--all']);
}

function commit() {
	return run('git', ['commit', '-m', '"[GIT AUTO COMMIT]: ' + new Date().toString() + '"']);
}

function push(){
  if(program.push !== undefined)
  {
    if(program.branch === undefined)
    {
      program.branch = "master";
    }
    return run('git',['push',program.push,program.branch]);
  } else {
    return Promise.resolve();
  }
}

setInterval(function() {
  Promise.resolve()
    .then(addAll)
    .then(commit)
    .then(push)
    .then(function() {
		console.log(('[GIT AUTO COMMIT]: Commit success at ' + (new Date()).toString()).green);
	}).catch(function (e) {
		console.log(('[GIT AUTO COMMIT]: ' + e.message).red);
	});
}, (program.time || 300) * 1000);<commit_msg>"[GIT AUTO COMMIT]: Sun Oct 08 2017 02:26:24 GMT+0200 (CEST)"<commit_after>#!/usr/bin/env node

require('colors');
var program = require('commander');
var promise = require('promise');
var spawn = require('child_process').spawn;
var pkg = require('./package.json');
var CWD = process.cwd();

var startDate = new Date();
var counter = 0;

program.version(pkg.version)
	.option('-t, --time <n>', 'seconds between two commits', parseFloat)
	.option('-p, --push <n>', 'push to specified remote after commit')
	.option('-b, --branch <n>', 'name of the branch to push')
	.parse(process.argv);

function run(command, args) {
  return new Promise(function(resolve, reject) {
    var task = spawn(command, args, {
    	cwd: CWD
    });
    task.on('close', function(code) {
      if (code !== 0) reject(new Error(command + ' process exited with code ' + code));
      else resolve();
    });
    task.stdout.pipe(process.stdout);
    task.stderr.pipe(process.stderr);
  });
}
function getFormattedDate(date)
{
  return date.getFullYear()+
        pad(d.getMonth())
        pad(d.getDate())+
        pad(d.getHours())+
        pad(d.getMinutes())+
        pad(d.getSeconds());
}
function addAll() {
	return run('git', ['add', '--all']);
}

function commit() {
  counter = counter + 1;
	return run('git', ['commit', '-m', '"[GIT AUTO COMMIT]: ' + new Date().toString() + '"']);
}

function push(){
  if(program.push !== undefined)
  {
    if(program.branch === undefined)
    {
      program.branch = "master";
    }
    return run('git',['push',program.push,program.branch]);
  } else {
    return Promise.resolve();
  }
}

setInterval(function() {
  Promise.resolve()
    .then(addAll)
    .then(commit)
    .then(push)
    .then(function() {
		console.log(('[GIT AUTO COMMIT]: Commit success at ' + (new Date()).toString()).green);
	}).catch(function (e) {
		console.log(('[GIT AUTO COMMIT]: ' + e.message).red);
	});
}, (program.time || 300) * 1000);<|endoftext|>


<commit_before>/*
 * Copyright 2017 Nicolas Lochet Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */

module.exports = (function() {
  'use strict'
  var Store = require('wool-store')

  function Rule(r, s) {
    if (! (this instanceof Rule)) return new Rule(r, s)
    this.rules = r.reduce(function(p, c) {
      var x = p[c.n] = {}
      x.n = c.n
      x.p = c.p
      if ('c' in c) { x.c = c.c.bind(this) }
      x.o = c.o.bind(this)
      return p
    }.bind(this), {})
    this.store = s || Store()
  }
  Rule.prototype.push = function(cmd, cb) {
    var rule = this.rules[cmd.n]
    if ('c' in rule) {
      return rule.c(cmd.d, function(err) {
        if (err) return cb(err)
        else try {
          return this.execute(rule, cmd, cb)
        } catch (e) {
          return cb(e)
        }
      }.bind(this))
    } else {
      return this.execute(rule, cmd, cb)
    }
  }
  Rule.prototype.execute = function(rule, cmd, cb) {
    return rule.o(cmd.d, function(err, data) {
      if (err) return cb(err)
      else try {
        return cb(err, data)
      } catch (e) {
        return cb(e)
      }
    }.bind(this))
  }
  Rule.prototype.get = function(id) {
    return this.store.get(id)
  }
  Rule.prototype.create = function(param, k, data, cb) {
    try {
      var id = (k in param) ? param[k] : param[k] = Store.newId()
      this.store.set(id, data)
      cb(null, param)
    } catch(e) {
      cb(e)
    }
  }
  Rule.prototype.update = function(id, data, cb) {
    try {
      this.store.set(id, data)
      cb(null)
    } catch(e) {
      cb(e)
    }
  }
  return Rule
}())
<commit_msg>improve example rule with session managed user, WIP<commit_after>/*
 * Copyright 2017 Nicolas Lochet Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */

module.exports = (function() {
  'use strict'
  var Store = require('wool-store')

  function Rule(r, s) {
    if (! (this instanceof Rule)) return new Rule(r, s)
    this.rules = r.reduce(function(p, c) {
      var x = p[c.n] = {}
      x.n = c.n
      x.p = c.p
      if ('c' in c) { x.c = c.c.bind(this) }
      x.o = c.o.bind(this)
      return p
    }.bind(this), {})
    this.store = s || Store()
  }
  Rule.prototype.push = function(cmd, cb) {
    var rule = this.rules[cmd.n]
    if ('c' in rule) {
      return rule.c(cmd.d, function(err) {
        if (err) return cb(err)
        else try {
          return this.execute(rule, cmd, cb)
        } catch (e) {
          return cb(e)
        }
      }.bind(this))
    } else {
      return this.execute(rule, cmd, cb)
    }
  }
  Rule.prototype.execute = function(rule, cmd, cb) {
    return rule.o(cmd.d, function(err, data) {
      if (err) return cb(err)
      else try {
        return cb(err, data)
      } catch (e) {
        return cb(e)
      }
    }.bind(this))
  }
  Rule.prototype.get = function(id) {
    return this.store.get(id)
  }
  Rule.prototype.create = function(f, data, cb) {
    try {
      var newId = Store.newId()
        , id = ((typeof f === 'function') ? f(newId) : ((typeof f === 'string') ? f+newId : newId))
      this.store.set(id, data)
      cb(null, param)
    } catch(e) {
      cb(e)
    }
  }
  Rule.prototype.update = function(id, data, cb) {
    try {
      this.store.set(id, data)
      cb(null)
    } catch(e) {
      cb(e)
    }
  }
  Rule.prototype.remove = function(id, cb) {
    try {
      this.store.del(id)
      cb(null)
    } catch(e) {
      cb(e)
    }
  }
  return Rule
}())
<|endoftext|>


<commit_before>var assert = require('assert');
var url = require('url');
var http = require('http');
var https = require('https');
var getRawBody = require('raw-body');

require('buffer');

module.exports = function proxy(host, options) {
  'use strict';

  assert(host, 'Host should not be empty');

  options = options || {};

  var parsedHost;

  /**
   * Function :: intercept(targetResponse, data, res, req, function(err, json));
   */
  var intercept = options.intercept;   // after request (5)
  var decorateRequest = options.decorateRequest;  // before request (2)
  var forwardPath = options.forwardPath || defaultForwardPath;  // before request (1)
  var filter = options.filter || defaultFilter;  // before request (0)
  var limit = options.limit || '1mb';  // option
  var preserveReqSession = options.preserveReqSession; // binary option

  return function handleProxy(req, res, next) {

    if (!filter(req, res)) { return next(); }

    var path = forwardPath(req, res);

    parsedHost = parsedHost || parseHost(host, req);

    if (req.body) {
      runProxy(null, req.body);
    } else {
      getRawBody(req, {
        length: req.headers['content-length'],
        limit: limit,
        encoding: bodyEncoding(options),
      }, runProxy);
    }

    function runProxy(err, bodyContent) {
      var reqOpt = {
        hostname: parsedHost.host,
        port: options.port || parsedHost.port,
        headers: reqHeaders(req, options),
        method: req.method,
        path: path,
        bodyContent: bodyContent,
        params: req.params,
      };

      if (preserveReqSession) {
        reqOpt.session = req.session;
      }

      if (decorateRequest) {
        reqOpt = decorateRequest(reqOpt, req) || reqOpt;
      }

      bodyContent = reqOpt.bodyContent;
      delete reqOpt.bodyContent;
      delete reqOpt.params;

      if (err && !bodyContent) {
        return next(err);
      }

      if (typeof bodyContent === 'string') {
        reqOpt.headers['content-length'] = Buffer.byteLength(bodyContent);
      } else if (Buffer.isBuffer(bodyContent)) { // Buffer
        reqOpt.headers['content-length'] = bodyContent.length;
      }

      var realRequest = parsedHost.module.request(reqOpt, function(rsp) {
        var chunks = [];

        rsp.on('data', function(chunk) {
          chunks.push(chunk);
        });

        rsp.on('end', function() {

          var rspData = Buffer.concat(chunks, length(chunks));

          if (intercept) {
            intercept(rsp, rspData, req, res, function(err, rspd, sent) {
              if (err) {
                return next(err);
              }

              var encode = 'utf8';

              if (typeof rspd === 'string') {
                rspd = new Buffer(rspd, encode);
              }

              if (!Buffer.isBuffer(rspd)) {
                next(new Error('intercept should return string or' +
                      'buffer as data'));
              }

              if (!res.headersSent) {
                res.set('content-length', rspd.length);
              } else if (rspd.length !== rspData.length) {
                var error = '"Content-Length" is already sent,' +
                      'the length of response data can not be changed';
                next(new Error(error));
              }

              if (!sent) {
                res.send(rspd);
              }
            });
          } else {
            res.send(rspData);
          }
        });

        rsp.on('error', function(e) {
          next(e);
        });

        if (!res.headersSent) {
          res.status(rsp.statusCode);
          Object.keys(rsp.headers)
            .filter(function(item) { return item !== 'transfer-encoding'; })
            .forEach(function(item) {
              res.set(item, rsp.headers[item]);
            });
        }
      });

      realRequest.on('socket', function(socket) {
        if (options.timeout) {
          socket.setTimeout(options.timeout, function() {
            realRequest.abort();
          });
        }
      });

      realRequest.on('error', function(err) {
        if (err.code === 'ECONNRESET') {
          res.setHeader('X-Timout-Reason',
            'express-http-proxy timed out your request after ' +
            options.timeout + 'ms.');
          res.writeHead(504, {'Content-Type': 'text/plain'});
          res.end();
          next();
        } else {
          next(err);
        }
      });

      if (bodyContent.length) {
        realRequest.write(bodyContent);
      }

      realRequest.end();

      req.on('aborted', function () {
        realRequest.abort();
      });
    }
  };
};

function extend(obj, source, skips) {
  'use strict';

  if (!source) {
    return obj;
  }

  for (var prop in source) {
    if (!skips || skips.indexOf(prop) === -1) {
      obj[prop] = source[prop];
    }
  }

  return obj;
}

function parseHost(host, req) {
  'use strict';

  host = (typeof host === 'function') ? host(req) : host.toString();

  if (!host) {
    return new Error('Empty host parameter');
  }

  if (!/http(s)?:\/\//.test(host)) {
    host = 'http://' + host;
  }

  var parsed = url.parse(host);

  if (!parsed.hostname) {
    return new Error('Unable to parse hostname, possibly missing protocol://?');
  }

  var ishttps = parsed.protocol === 'https:';

  return {
    host: parsed.hostname,
    port: parsed.port || (ishttps ? 443 : 80),
    module: ishttps ? https : http,
  };
}

function reqHeaders(req, options) {
  'use strict';

  var headers = options.headers || {};

  var skipHdrs = [ 'connection', 'content-length' ];
  if (!options.preserveHostHdr) {
    skipHdrs.push('host');
  }
  var hds = extend(headers, req.headers, skipHdrs);
  hds.connection = 'close';

  return hds;
}

function defaultFilter() {
  // No-op version of filter.  Allows everything!
  'use strict';
  return true;
}

function defaultForwardPath(req) {
  'use strict';
  return url.parse(req.url).path;
}

function bodyEncoding(options) {
  'use strict';

  /* For reqBodyEncoding, these is a meaningful difference between null and
   * undefined.  null should be passed forward as the value of reqBodyEncoding,
   * and undefined should result in utf-8.
   */

  return options.reqBodyEncoding !== undefined ? options.reqBodyEncoding: 'utf-8';
}

function length(chunks) {
  'use strict';

  return chunks.reduce(function(len, buf) {
    return len + buf.length;
  }, 0);
}
<commit_msg>[adhoc] Whitespace fix.<commit_after>var assert = require('assert');
var url = require('url');
var http = require('http');
var https = require('https');
var getRawBody = require('raw-body');

require('buffer');

module.exports = function proxy(host, options) {
  'use strict';

  assert(host, 'Host should not be empty');

  options = options || {};

  var parsedHost;

  /**
   * Function :: intercept(targetResponse, data, res, req, function(err, json));
   */
  var intercept = options.intercept;   // after request (5)
  var decorateRequest = options.decorateRequest;  // before request (2)
  var forwardPath = options.forwardPath || defaultForwardPath;  // before request (1)
  var filter = options.filter || defaultFilter;  // before request (0)
  var limit = options.limit || '1mb';  // option
  var preserveReqSession = options.preserveReqSession; // binary option

  return function handleProxy(req, res, next) {

    if (!filter(req, res)) { return next(); }

    var path = forwardPath(req, res);

    parsedHost = parsedHost || parseHost(host, req);

    if (req.body) {
      runProxy(null, req.body);
    } else {
      getRawBody(req, {
        length: req.headers['content-length'],
        limit: limit,
        encoding: bodyEncoding(options),
      }, runProxy);
    }

    function runProxy(err, bodyContent) {
      var reqOpt = {
        hostname: parsedHost.host,
        port: options.port || parsedHost.port,
        headers: reqHeaders(req, options),
        method: req.method,
        path: path,
        bodyContent: bodyContent,
        params: req.params,
      };

      if (preserveReqSession) {
        reqOpt.session = req.session;
      }

      if (decorateRequest) {
        reqOpt = decorateRequest(reqOpt, req) || reqOpt;
      }

      bodyContent = reqOpt.bodyContent;
      delete reqOpt.bodyContent;
      delete reqOpt.params;

      if (err && !bodyContent) {
        return next(err);
      }

      if (typeof bodyContent === 'string') {
        reqOpt.headers['content-length'] = Buffer.byteLength(bodyContent);
      } else if (Buffer.isBuffer(bodyContent)) { // Buffer
        reqOpt.headers['content-length'] = bodyContent.length;
      }

      var realRequest = parsedHost.module.request(reqOpt, function(rsp) {
        var chunks = [];

        rsp.on('data', function(chunk) {
          chunks.push(chunk);
        });

        rsp.on('end', function() {

          var rspData = Buffer.concat(chunks, length(chunks));

          if (intercept) {
            intercept(rsp, rspData, req, res, function(err, rspd, sent) {
              if (err) {
                return next(err);
              }

              var encode = 'utf8';

              if (typeof rspd === 'string') {
                rspd = new Buffer(rspd, encode);
              }

              if (!Buffer.isBuffer(rspd)) {
                next(new Error('intercept should return string or' +
                      'buffer as data'));
              }

              if (!res.headersSent) {
                res.set('content-length', rspd.length);
              } else if (rspd.length !== rspData.length) {
                var error = '"Content-Length" is already sent,' +
                      'the length of response data can not be changed';
                next(new Error(error));
              }

              if (!sent) {
                res.send(rspd);
              }
            });
          } else {
            res.send(rspData);
          }
        });

        rsp.on('error', function(e) {
          next(e);
        });

        if (!res.headersSent) {
          res.status(rsp.statusCode);
          Object.keys(rsp.headers)
            .filter(function(item) { return item !== 'transfer-encoding'; })
            .forEach(function(item) {
              res.set(item, rsp.headers[item]);
            });
        }
      });

      realRequest.on('socket', function(socket) {
        if (options.timeout) {
          socket.setTimeout(options.timeout, function() {
            realRequest.abort();
          });
        }
      });

      realRequest.on('error', function(err) {
        if (err.code === 'ECONNRESET') {
          res.setHeader('X-Timout-Reason',
            'express-http-proxy timed out your request after ' +
            options.timeout + 'ms.');
          res.writeHead(504, {'Content-Type': 'text/plain'});
          res.end();
          next();
        } else {
          next(err);
        }
      });

      if (bodyContent.length) {
        realRequest.write(bodyContent);
      }

      realRequest.end();

      req.on('aborted', function() {
        realRequest.abort();
      });
    }
  };
};

function extend(obj, source, skips) {
  'use strict';

  if (!source) {
    return obj;
  }

  for (var prop in source) {
    if (!skips || skips.indexOf(prop) === -1) {
      obj[prop] = source[prop];
    }
  }

  return obj;
}

function parseHost(host, req) {
  'use strict';

  host = (typeof host === 'function') ? host(req) : host.toString();

  if (!host) {
    return new Error('Empty host parameter');
  }

  if (!/http(s)?:\/\//.test(host)) {
    host = 'http://' + host;
  }

  var parsed = url.parse(host);

  if (!parsed.hostname) {
    return new Error('Unable to parse hostname, possibly missing protocol://?');
  }

  var ishttps = parsed.protocol === 'https:';

  return {
    host: parsed.hostname,
    port: parsed.port || (ishttps ? 443 : 80),
    module: ishttps ? https : http,
  };
}

function reqHeaders(req, options) {
  'use strict';

  var headers = options.headers || {};

  var skipHdrs = [ 'connection', 'content-length' ];
  if (!options.preserveHostHdr) {
    skipHdrs.push('host');
  }
  var hds = extend(headers, req.headers, skipHdrs);
  hds.connection = 'close';

  return hds;
}

function defaultFilter() {
  // No-op version of filter.  Allows everything!
  'use strict';
  return true;
}

function defaultForwardPath(req) {
  'use strict';
  return url.parse(req.url).path;
}

function bodyEncoding(options) {
  'use strict';

  /* For reqBodyEncoding, these is a meaningful difference between null and
   * undefined.  null should be passed forward as the value of reqBodyEncoding,
   * and undefined should result in utf-8.
   */

  return options.reqBodyEncoding !== undefined ? options.reqBodyEncoding: 'utf-8';
}

function length(chunks) {
  'use strict';

  return chunks.reduce(function(len, buf) {
    return len + buf.length;
  }, 0);
}
<|endoftext|>


<commit_before>var moment = require('moment');
var parseDates = require('./lib/parse');

module.exports = function(options) {
  options = options || {};

  if (typeof options.format === 'undefined') {
    options.formats = ['x', 'MM-DD-YYYY', moment.ISO_8601];
  }

  if (typeof options.strict === 'undefined') {
    options.strict = true;
  }

  return function(req, res, next) {
    req.query = parseDates(req.query, options);
    next();
  };
};
<commit_msg>Fix formats always getting overriden. Default to less error prone format.<commit_after>var moment = require('moment');
var parseDates = require('./lib/parse');

module.exports = function(options) {
  options = options || {};

  if (typeof options.formats === 'undefined') {
    options.formats = [moment.ISO_8601];
  }

  if (typeof options.strict === 'undefined') {
    options.strict = true;
  }

  return function(req, res, next) {
    req.query = parseDates(req.query, options);
    next();
  };
};
<|endoftext|>


<commit_before>var passport = require('passport'),
    express = require('express');

// constant fields
const MAX_SAFE_INTEGER = 9007199254740991;

// Create a router to attractions
var router = express.Router();

// Find project working directory
var src = process.cwd() + '/src/';

var error = require(src + 'helpers/error'),
    log   = require(src + 'helpers/log')(module);

var georedis = require(src + 'helpers/georedis');

// Regex expressions to test input latitude and longitude
var regExpLatitude  = /^(\+|-)?(?:90(?:(?:\.0{1,8})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,8})?))$/,
    regExpLongitude = /^(\+|-)?(?:180(?:(?:\.0{1,8})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,8})?))$/;

// Load Models
var Point = require(src + 'models/point');

router.get('/name', passport.authenticate('bearer', { session: false }), function (req, res) {
    var text = req.query.text;

    if (!text) {
        error.genericErrorHandler(res, 400, "user_error", "Some input text is required in this search!");
    } else {
        var message,
            query = [
                {name: { $regex: text, $options: 'i' }}, {description: { $regex: text, $options: 'i' }},
                {category: { $regex: text, $options: 'i' }}, {keywords: text}
            ];

        var page   = Math.min(req.query.page, MAX_SAFE_INTEGER),
            offset = page !== MAX_SAFE_INTEGER ? Math.max(req.query.offset - 1, 0) : 0;

        Point.find({ $or: query })
            .limit(page)
            .skip(page * offset)
            .sort({ updated: 'desc'})
            .populate('localization')
            .exec(function (err, points) {
                if (err) {
                    log.error(err.message);

                    error.genericErrorHandler(res, 500, "server_error", "mongodb_error")
                } else {
                    if (!points.length)
                        // Request result not in an Error, but any point was found
                        message = "Not found any point that matches with input text";
                    else
                        // Request result not in an Error
                        message = "Were found points that matches with input text";
                }
                log.info(message);
                res.json({points: points, status: "ok", message: message});
            });
    }
});

router.get('/points', passport.authenticate('bearer', { session: false }), function(req, res) {
    var latitude  = req.query.latitude,
        longitude = req.query.longitude,
        distance  = parseInt(req.query.distance, 10) || 5000;

    if (!latitude || !longitude) {
        error.genericErrorHandler(res, 400, "user_error", "Latitude and Longitude is required in this search!");
    } else if(!regExpLatitude.test(latitude) || !regExpLongitude.test(longitude)) {
        error.genericErrorHandler(res, 400, "user_error", "Invalid Latitude or Longitude matches!");
    } else {
        var message;
        georedis.searchNearbyLocalizations(latitude, longitude, distance, function (err, result) {
            if (err) {
                log.error(err.message);

                error.genericErrorHandler(res, 500, "server_error", "Search engine error");
            } else if (!result.length) {
                // Request result not in an Error, but any point was found
                message = "Not found any point near the input coordinates";

                log.info(message);
                res.json({points: [], status: 'ok', message: message});
            } else {
                var page   = Math.min(req.query.page, MAX_SAFE_INTEGER),
                    offset = page !== MAX_SAFE_INTEGER ? Math.max(req.query.offset - 1, 0) : 0;

                Point.find({_id: { $in: result }})
                    .limit(page)
                    .skip(page * offset)
                    .sort({ updated: 'desc'})
                    .populate('localization')
                    .exec(function (err, points) {
                        if (err) {
                            log.error(err.message);

                            error.genericErrorHandler(res, 500, "server_error", "mongodb_error")
                        } else {
                            // Request result not in an Error
                            message = "Were found points near the input coordinates";

                            log.info(message);
                            res.json({points: points, status: "ok", message: message});
                        }
                    });
            }
        })
    }
});

router.get('/full/points', passport.authenticate('bearer', { session: false }), function(req, res) {
    var latitude  = req.query.latitude,
        longitude = req.query.longitude,
        distance  = parseInt(req.query.distance, 10) || 5000;

    if (!latitude || !longitude) {
        error.genericErrorHandler(res, 400, "user_error", "Latitude and Longitude is required in this search!");
    } else if(!regExpLatitude.test(latitude) || !regExpLongitude.test(longitude)) {
        error.genericErrorHandler(res, 400, "user_error", "Invalid Latitude or Longitude matches!");
    } else {
        var message;
        georedis.searchNearbyLocalizations(latitude, longitude, distance, function (err, result) {
            if (err) {
                log.error(err.message);

                error.genericErrorHandler(res, 500, "server_error", "Search engine error");
            } else if (!result.length) {
                // Request result not in an Error, but any point was found
                message = "Not found any point near the input coordinates";

                log.info(message);
                res.json({points: [], status: 'ok', message: message});
            } else {
                var page   = Math.min(req.query.page, MAX_SAFE_INTEGER),
                    offset = page !== MAX_SAFE_INTEGER ? Math.max(req.query.offset - 1, 0) : 0;

                Point.find({_id: { $in: result }})
                    .limit(page)
                    .skip(page * offset)
                    .sort({ updated: 'desc'})
                    .populate('localization', 'photos', 'photo')
                    .exec(function (err, points) {
                        if (err) {
                            log.error(err.message);

                            error.genericErrorHandler(res, 500, "server_error", "mongodb_error")
                        } else {
                            // Request result not in an Error
                            message = "Were found points near the input coordinates";

                            log.info(message);
                            res.json({points: points, status: "ok", message: message});
                        }
                    });
            }
        })
    }
});

module.exports = router;
<commit_msg>Remove route to request points and images in same request<commit_after>var passport = require('passport'),
    express = require('express');

// constant fields
const MAX_SAFE_INTEGER = 9007199254740991;

// Create a router to attractions
var router = express.Router();

// Find project working directory
var src = process.cwd() + '/src/';

var error = require(src + 'helpers/error'),
    log   = require(src + 'helpers/log')(module);

var georedis = require(src + 'helpers/georedis');

// Regex expressions to test input latitude and longitude
var regExpLatitude  = /^(\+|-)?(?:90(?:(?:\.0{1,8})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,8})?))$/,
    regExpLongitude = /^(\+|-)?(?:180(?:(?:\.0{1,8})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,8})?))$/;

// Load Models
var Point = require(src + 'models/point');

router.get('/name', passport.authenticate('bearer', { session: false }), function (req, res) {
    var text = req.query.text;

    if (!text) {
        error.genericErrorHandler(res, 400, "user_error", "Some input text is required in this search!");
    } else {
        var message,
            query = [
                {name: { $regex: text, $options: 'i' }}, {description: { $regex: text, $options: 'i' }},
                {category: { $regex: text, $options: 'i' }}, {keywords: text}
            ];

        var page   = Math.min(req.query.page, MAX_SAFE_INTEGER),
            offset = page !== MAX_SAFE_INTEGER ? Math.max(req.query.offset - 1, 0) : 0;

        Point.find({ $or: query })
            .limit(page)
            .skip(page * offset)
            .sort({ updated: 'desc'})
            .populate('localization')
            .exec(function (err, points) {
                if (err) {
                    log.error(err.message);

                    error.genericErrorHandler(res, 500, "server_error", "mongodb_error")
                } else {
                    if (!points.length)
                        // Request result not in an Error, but any point was found
                        message = "Not found any point that matches with input text";
                    else
                        // Request result not in an Error
                        message = "Were found points that matches with input text";
                }
                log.info(message);
                res.json({points: points, status: "ok", message: message});
            });
    }
});

router.get('/points', passport.authenticate('bearer', { session: false }), function(req, res) {
    var latitude  = req.query.latitude,
        longitude = req.query.longitude,
        distance  = parseInt(req.query.distance, 10) || 5000;

    if (!latitude || !longitude) {
        error.genericErrorHandler(res, 400, "user_error", "Latitude and Longitude is required in this search!");
    } else if(!regExpLatitude.test(latitude) || !regExpLongitude.test(longitude)) {
        error.genericErrorHandler(res, 400, "user_error", "Invalid Latitude or Longitude matches!");
    } else {
        var message;
        georedis.searchNearbyLocalizations(latitude, longitude, distance, function (err, result) {
            if (err) {
                log.error(err.message);

                error.genericErrorHandler(res, 500, "server_error", "Search engine error");
            } else if (!result.length) {
                // Request result not in an Error, but any point was found
                message = "Not found any point near the input coordinates";

                log.info(message);
                res.json({points: [], status: 'ok', message: message});
            } else {
                var page   = Math.min(req.query.page, MAX_SAFE_INTEGER),
                    offset = page !== MAX_SAFE_INTEGER ? Math.max(req.query.offset - 1, 0) : 0;

                Point.find({_id: { $in: result }})
                    .limit(page)
                    .skip(page * offset)
                    .sort({ updated: 'desc'})
                    .populate('localization')
                    .exec(function (err, points) {
                        if (err) {
                            log.error(err.message);

                            error.genericErrorHandler(res, 500, "server_error", "mongodb_error")
                        } else {
                            // Request result not in an Error
                            message = "Were found points near the input coordinates";

                            log.info(message);
                            res.json({points: points, status: "ok", message: message});
                        }
                    });
            }
        })
    }
});

module.exports = router;
<|endoftext|>


<commit_before>'use strict'
try {
  module.exports = require('./bindings')
} catch (err) {
  console.log('Secp256k1 bindings are not compiled. Pure JS implementation will be used.')
  module.exports = require('./elliptic')
}
<commit_msg>Show warning only if DEBUG set<commit_after>'use strict'
try {
  module.exports = require('./bindings')
} catch (err) {
  if (process.env.DEBUG) {
    console.error('Secp256k1 bindings are not compiled. Pure JS implementation will be used.')
  }

  module.exports = require('./elliptic')
}
<|endoftext|>


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

/** run from commandline:
 * node index.js
 * -master /home/alexey/IdeaProjects/eslint-teamcity-failed-conditions/spec/fixtures/error.json
 * -current /home/alexey/IdeaProjects/eslint-teamcity-failed-conditions/spec/fixtures/empty.json
 */
/* eslint-env es6:true */
'use-strict';
const fs = require('fs-extra'),
      path = require('path'),
      ensureArray = require('ensure-array'),
      procArg = process.argv,
      allowedModes = {
        eslint: 'eslint'
      };

let currentExecutionMode = '';

if (require.main === module) {
  currentExecutionMode = 'console';
  main(procArg.slice(1));
} else {
  currentExecutionMode = 'module';
  module.exports = main;
}

/**
 *
 * @param args
 * @return {Promise}
 */
function main (args) {
  let currentMode = getCurrentMode(args);

  return runChecks(currentMode, args);
};

/**
 * Определить текущий режим работы
 * @param {Array} - mainArgs массив аргументов коммандной
 * @return {String} - режим
 */
function getCurrentMode (mainArgs) {
  let currentMode;

  for (let mode in allowedModes) {
    if ((currentExecutionMode === 'console' && mainArgs.indexOf(mode) === -1) ||
        (mainArgs.mode && mainArgs.mode.indexOf(mode) === -1)) {
      // TODO: вынести сообщения об ошибках в хелпер
      throw new Error(`Поддерживаемый режим работы не передан
       ${Object.keys(allowedModes)}`);
    } else {
      currentMode = mode;
      break;
    }
  };

  return currentMode;
};

/**
 * Запустить проверки
 * @param {String} mode - режим
 * @param {Aray} mainArgs - аргументы
 * @return {Promise} - обещание оеончания проверки
 */
function runChecks (mode, mainArgs) {
  let checkCompletePromise,
      preparedInput;
  switch (mode) {
    case allowedModes.eslint:
      preparedInput = prepareInput(mode, mainArgs);
      checkCompletePromise = require(path.resolve(__dirname, 'lib/eslint')).apply(null, preparedInput)
          .then((mergeResult) => {
              console.log(ensureArray(mergeResult).length === 0);
              return ensureArray(mergeResult).length === 0;
          })
          .catch((e) => {
              throw new Error(e);
          });
  }

  return checkCompletePromise;
}

/**
 * Подготовить входные данные для режима
 * @param {String} mode - режим
 * @param {Aray} mainArgs - аргументы
 * @return {Array} подготовленные входные данные
 */
function prepareInput (mode, mainArgs) {
  let currentJSON,
      masterJSON,
      resultJSONPath,
      input;

  switch (mode) {
    case allowedModes.eslint:
      if (currentExecutionMode === 'console') {
        currentJSON = fs.readJSONSync(`${mainArgs[mainArgs.indexOf('-current') + 1]}`);
        masterJSON = fs.readJSONSync(`${mainArgs[mainArgs.indexOf('-master') + 1]}`);
        resultJSONPath = path.resolve(mainArgs.indexOf('-result') !== -1 ? mainArgs[mainArgs.indexOf('-result') + 1] : path.dirname(mainArgs[1]), `result.json`);
      } else {
        currentJSON = fs.readJSONSync(mainArgs.currentJson);
        masterJSON = fs.readJSONSync(mainArgs.masterJSON);
        resultJSONPath = mainArgs.resultJSON ? mainArgs.resultJSON : path.resolve(path.dirname(procArg[1]), `result.json`);
      }
      // FIXME возвращать в виде объекта, использовать деструктуризацию
      input = [masterJSON, currentJSON, resultJSONPath];
  }

  return input;
}

/**
 * Выставление статуса
 * @param {Boolean} isSuccess
 * @param {String} [reason='']
 */
function reportStatus (isSuccess, reason) {
  let _reason = reason ? `=== Reason: ${reason}` : '';
  console.log(`\n\n=== Build ${isSuccess ? 'Success' : 'Failed'}\n${_reason}`);
};
<commit_msg>doc(*): добавлены примеры использованиявкомментарии<commit_after>#!/usr/bin/env node

/** run from commandline:
 * node index.js
 * eslint
 * -master /home/alexey/IdeaProjects/eslint-teamcity-failed-conditions/spec/fixtures/error.json
 * -current /home/alexey/IdeaProjects/eslint-teamcity-failed-conditions/spec/fixtures/empty.json
 * teamcity
 * -login testUsername
 * -pass testPassword
 * -host testHost
 * -projectId testProjectId
 * -buildId testBuildId
 */

/**
 * run as nodejs module
 * const buildFailedConditions = require('buildFailedConditions');
 * let config = {eslint: {}, teamcity: {}};
 * config.eslint = {
    masterJSON: `/home/alexey/IdeaProjects/eslint-teamcity-failed-conditions/spec/fixtures/error.json`,
    currentJson: `/home/alexey/IdeaProjects/eslint-teamcity-failed-conditions/spec/fixtures/empty.json`
  };
 * config.teamcity = {
    login: testUsername,
    pass: testPassword,
    host: testHost,
    projectId: testProjectId,
    buildId: testBuildId
  };
 * console.log(buildFailedConditions(config));
 */
/* eslint-env es6:true */
'use-strict';
const fs = require('fs-extra'),
      path = require('path'),
      ensureArray = require('ensure-array'),
      procArg = process.argv,
      allowedModes = {
        eslint: 'eslint'
      };

let currentExecutionMode = '';

if (require.main === module) {
  currentExecutionMode = 'console';
  main(procArg.slice(1));
} else {
  currentExecutionMode = 'module';
  module.exports = main;
}

/**
 *
 * @param args
 * @return {Promise}
 */
function main (args) {
  let currentMode = getCurrentMode(args);

  return runChecks(currentMode, args);
};

/**
 * Определить текущий режим работы
 * @param {Array} - mainArgs массив аргументов коммандной
 * @return {String} - режим
 */
function getCurrentMode (mainArgs) {
  let currentMode;

  for (let mode in allowedModes) {
    if ((currentExecutionMode === 'console' && mainArgs.indexOf(mode) === -1) ||
        (mainArgs.mode && mainArgs.mode.indexOf(mode) === -1)) {
      // TODO: вынести сообщения об ошибках в хелпер
      throw new Error(`Поддерживаемый режим работы не передан
       ${Object.keys(allowedModes)}`);
    } else {
      currentMode = mode;
      break;
    }
  };

  return currentMode;
};

/**
 * Запустить проверки
 * @param {String} mode - режим
 * @param {Aray} mainArgs - аргументы
 * @return {Promise} - обещание оеончания проверки
 */
function runChecks (mode, mainArgs) {
  let checkCompletePromise,
      preparedInput;
  switch (mode) {
    case allowedModes.eslint:
      preparedInput = prepareInput(mode, mainArgs);
      checkCompletePromise = require(path.resolve(__dirname, 'lib/eslint')).apply(null, preparedInput)
          .then((mergeResult) => {
              console.log(ensureArray(mergeResult).length === 0);
              return ensureArray(mergeResult).length === 0;
          })
          .catch((e) => {
              throw new Error(e);
          });
  }

  return checkCompletePromise;
}

/**
 * Подготовить входные данные для режима
 * @param {String} mode - режим
 * @param {Aray} mainArgs - аргументы
 * @return {Array} подготовленные входные данные
 */
function prepareInput (mode, mainArgs) {
  let currentJSON,
      masterJSON,
      resultJSONPath,
      input;

  switch (mode) {
    case allowedModes.eslint:
      if (currentExecutionMode === 'console') {
        currentJSON = fs.readJSONSync(`${mainArgs[mainArgs.indexOf('-current') + 1]}`);
        masterJSON = fs.readJSONSync(`${mainArgs[mainArgs.indexOf('-master') + 1]}`);
        resultJSONPath = path.resolve(mainArgs.indexOf('-result') !== -1 ? mainArgs[mainArgs.indexOf('-result') + 1] : path.dirname(mainArgs[1]), `result.json`);
      } else {
        currentJSON = fs.readJSONSync(mainArgs.currentJson);
        masterJSON = fs.readJSONSync(mainArgs.masterJSON);
        resultJSONPath = mainArgs.resultJSON ? mainArgs.resultJSON : path.resolve(path.dirname(procArg[1]), `result.json`);
      }
      // FIXME возвращать в виде объекта, использовать деструктуризацию
      input = [masterJSON, currentJSON, resultJSONPath];
  }

  return input;
}

/**
 * Выставление статуса
 * @param {Boolean} isSuccess
 * @param {String} [reason='']
 */
function reportStatus (isSuccess, reason) {
  let _reason = reason ? `=== Reason: ${reason}` : '';
  console.log(`\n\n=== Build ${isSuccess ? 'Success' : 'Failed'}\n${_reason}`);
};
<|endoftext|>


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

require('lazy-ass');
var ecstatic = require('ecstatic');
var check = require('check-types');
var istanbul = require('istanbul');
var Collector = istanbul.Collector;
var instrumenter = new istanbul.Instrumenter();
var fs = require('fs');
var path = require('path');
var optimist = require('optimist');
var http = require('http'),
  httpProxy = require('http-proxy');
var savedReportDir = './html-report';
var pkg = require('./package.json');
var info = pkg.name + ' - ' + pkg.description + '\n' +
    '  version: ' + pkg.version + '\n' +
    '  author: ' + JSON.stringify(pkg.author);

require('./src/check-updates')();

var program = optimist
  .option('version', {
    boolean: true,
    alias: 'v',
    description: 'show version and exit',
    default: false
  })
  .option('target', {
    string: true,
    alias: 't',
    description: 'target server url',
    default: 'http://127.0.0.1:3003'
  })
  .option('port', {
    number: true,
    alias: 'p',
    description: 'local proxy port',
    default: 5050
  })
  .option('instrument', {
    string: true,
    alias: 'i',
    description: 'instrument url RegExp',
    default: 'app.js$'
  })
  .option('reset', {
    boolean: true,
    alias: 'r',
    description: 'erase previously collected coverage',
    default: false
  })
  .usage(info)
  .argv;

if (program.version) {
  console.log(info);
  process.exit(0);
}

if (program.help || program.h) {
  optimist.showHelp();
  process.exit(0);
}

la(check.unemptyString(program.target), 'missing target server url', program);

function shouldInstrument(regex, url) {
  la(check.instance(regex, RegExp), 'not a regex', regex);
  la(check.unemptyString(url), 'expected url string');
  return regex.test(url);
}

var shouldBeInstrumented = shouldInstrument.bind(null, new RegExp(program.instrument));

var setupCoverageSend = require('./src/send-coverage');
la(check.fn(setupCoverageSend), 'missing send coverage function');

function writeCoverageReports(coverage) {
  la(check.object(coverage), 'missing coverage object');
  var Report = istanbul.Report;

  var collector = new Collector();
  collector.add(coverage);

  var summaryReport = Report.create('text-summary');
  summaryReport.writeReport(collector);
  var htmlReport = Report.create('html');
  htmlReport.writeReport(collector, true);
}

var coverageFilename = path.join(savedReportDir, 'coverage.json');

function resetCoverage() {
  if (fs.existsSync(coverageFilename)) {
    fs.unlinkSync(coverageFilename);
    console.log('deleted previous coverage file', coverageFilename);
  }
}

if (program.reset) {
  resetCoverage();
}

if (!fs.existsSync(savedReportDir)) {
  fs.mkdirSync(savedReportDir);
  console.log('created folder', savedReportDir);
}

function combineCoverage(coverage) {
  var collector = new Collector();
  if (fs.existsSync(coverageFilename)) {
    collector.add(JSON.parse(fs.readFileSync(coverageFilename, 'utf8')));
  }
  collector.add(coverage);
  var combined = collector.getFinalCoverage();
  fs.writeFileSync(coverageFilename, JSON.stringify(combined, null, '  '));
  console.log('saved combined coverage to', coverageFilename);
  return combined;
}

function prepareSaveDir() {
  var saveFolder = './scripts/';
  if (!fs.existsSync(saveFolder)) {
    fs.mkdirSync(saveFolder);
  }
  return saveFolder;
}
var saveFolder = prepareSaveDir();

function saveSourceFile(src, url) {
  la(check.unemptyString(src), 'missing file source');
  la(check.unemptyString(url), 'missing url');

  // just leave filename
  var stripParams = url.replace(/\?.*$/, '');
  var lastSlash = stripParams.lastIndexOf('/');
  if (lastSlash !== -1) {
    stripParams = stripParams.substr(lastSlash + 1);
  }
  var filename = stripParams;
  console.log('url', url, 'filename', filename);

  var fullFilename = path.join(saveFolder, filename);
  fs.writeFileSync(fullFilename, src);
  return fullFilename;
}

function prepareResponseSelectors(proxyRes, req, res) {
  var _write      = res.write;
  var _end        = res.end;
  var _writeHead  = res.writeHead;
  var scriptSrc = '';

  res.writeHead = function (code, headers) {
    if (code === 304) {
      scriptSrc = '';
      return _writeHead.apply(res, arguments);
    }
    var contentType = this.getHeader('content-type');
    console.log('writing head', contentType);
    la(check.unemptyString(contentType), 'missing content type for code', code);

    // Strip off the content length since it will change.
    res.removeHeader('Content-Length');
    if (headers) {
      delete headers['content-length'];
    }
    _writeHead.apply(res, arguments);
  };

  res.write = function (chunk) {
    scriptSrc += chunk;
  };

  res.end = function (data) {
    if (data) {
      scriptSrc += data;
    }
    if (scriptSrc) {
      var filename = saveSourceFile(scriptSrc, req.url);
      var instrumented = instrumenter.instrumentSync(scriptSrc, filename);
      instrumented += '\n\n';
      instrumented += setupCoverageSend.toString() + '\n';
      instrumented += 'setupCoverageSend();\n';
      _write.call(res, instrumented);
    }
    _end.call(res);
  };
}

//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});
var getReportUrlPrefix = '__report/';

var reportServer = ecstatic({
  root: savedReportDir,
  baseDir: getReportUrlPrefix
});

function isGetReportRequest(url) {
  return url.indexOf(getReportUrlPrefix) === 1;
}

//
// Create your custom server and just call `proxy.web()` to proxy
// a web request to the target passed in the options
// also you can use `proxy.ws()` to proxy a websockets request
//
var server = http.createServer(function (req, res) {
  // You can define here your custom logic to handle the request
  // and then proxy the request.

  if (req.method === 'GET' && isGetReportRequest(req.url)) {
    console.log('coverage report', req.url);
    reportServer(req, res);
  } else if (req.method === 'GET' && req.url === '/__reset') {
    resetCoverage();
    res.writeHead(200);
    res.end();
  } else if (req.method === 'POST' && req.url === '/__coverage') {
    console.log('received coverage info');
    var str = '';
    req.on('data', function (chunk) {
      str += chunk;
    });
    req.on('end', function () {
      var coverage = JSON.parse(str);
      var combined = combineCoverage(coverage);
      writeCoverageReports(combined);
    });
    res.writeHead(200);
    res.end();
  } else {
    console.log('proxy', req.method, req.url);
    proxy.web(req, res, { target: program.target });
  }
});

proxy.on('proxyRes', function (proxyRes, req, res) {
  // console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
  if (shouldBeInstrumented(req.url)) {
    console.log('will instrument', req.url);
    prepareResponseSelectors(proxyRes, req, res);
  }
});

console.log(pkg.name, 'listening on port', program.port);
server.listen(program.port);
<commit_msg>printing codes<commit_after>#!/usr/bin/env node

require('lazy-ass');
var ecstatic = require('ecstatic');
var check = require('check-types');
var istanbul = require('istanbul');
var Collector = istanbul.Collector;
var instrumenter = new istanbul.Instrumenter();
var fs = require('fs');
var path = require('path');
var optimist = require('optimist');
var http = require('http'),
  httpProxy = require('http-proxy');
var savedReportDir = './html-report';
var pkg = require('./package.json');
var info = pkg.name + ' - ' + pkg.description + '\n' +
    '  version: ' + pkg.version + '\n' +
    '  author: ' + JSON.stringify(pkg.author);

require('./src/check-updates')();

var program = optimist
  .option('version', {
    boolean: true,
    alias: 'v',
    description: 'show version and exit',
    default: false
  })
  .option('target', {
    string: true,
    alias: 't',
    description: 'target server url',
    default: 'http://127.0.0.1:3003'
  })
  .option('port', {
    number: true,
    alias: 'p',
    description: 'local proxy port',
    default: 5050
  })
  .option('instrument', {
    string: true,
    alias: 'i',
    description: 'instrument url RegExp',
    default: 'app.js$'
  })
  .option('reset', {
    boolean: true,
    alias: 'r',
    description: 'erase previously collected coverage',
    default: false
  })
  .usage(info)
  .argv;

if (program.version) {
  console.log(info);
  process.exit(0);
}

if (program.help || program.h) {
  optimist.showHelp();
  process.exit(0);
}

la(check.unemptyString(program.target), 'missing target server url', program);

function shouldInstrument(regex, url) {
  la(check.instance(regex, RegExp), 'not a regex', regex);
  la(check.unemptyString(url), 'expected url string');
  return regex.test(url);
}

var shouldBeInstrumented = shouldInstrument.bind(null, new RegExp(program.instrument));

var setupCoverageSend = require('./src/send-coverage');
la(check.fn(setupCoverageSend), 'missing send coverage function');

function writeCoverageReports(coverage) {
  la(check.object(coverage), 'missing coverage object');
  var Report = istanbul.Report;

  var collector = new Collector();
  collector.add(coverage);

  var summaryReport = Report.create('text-summary');
  summaryReport.writeReport(collector);
  var htmlReport = Report.create('html');
  htmlReport.writeReport(collector, true);
}

var coverageFilename = path.join(savedReportDir, 'coverage.json');

function resetCoverage() {
  if (fs.existsSync(coverageFilename)) {
    fs.unlinkSync(coverageFilename);
    console.log('deleted previous coverage file', coverageFilename);
  }
}

if (program.reset) {
  resetCoverage();
}

if (!fs.existsSync(savedReportDir)) {
  fs.mkdirSync(savedReportDir);
  console.log('created folder', savedReportDir);
}

function combineCoverage(coverage) {
  var collector = new Collector();
  if (fs.existsSync(coverageFilename)) {
    collector.add(JSON.parse(fs.readFileSync(coverageFilename, 'utf8')));
  }
  collector.add(coverage);
  var combined = collector.getFinalCoverage();
  fs.writeFileSync(coverageFilename, JSON.stringify(combined, null, '  '));
  console.log('saved combined coverage to', coverageFilename);
  return combined;
}

function prepareSaveDir() {
  var saveFolder = './scripts/';
  if (!fs.existsSync(saveFolder)) {
    fs.mkdirSync(saveFolder);
  }
  return saveFolder;
}
var saveFolder = prepareSaveDir();

function saveSourceFile(src, url) {
  la(check.unemptyString(src), 'missing file source');
  la(check.unemptyString(url), 'missing url');

  // just leave filename
  var stripParams = url.replace(/\?.*$/, '');
  var lastSlash = stripParams.lastIndexOf('/');
  if (lastSlash !== -1) {
    stripParams = stripParams.substr(lastSlash + 1);
  }
  var filename = stripParams;
  console.log('url', url, 'filename', filename);

  var fullFilename = path.join(saveFolder, filename);
  fs.writeFileSync(fullFilename, src);
  return fullFilename;
}

function prepareResponseSelectors(proxyRes, req, res) {
  var _write      = res.write;
  var _end        = res.end;
  var _writeHead  = res.writeHead;
  var scriptSrc = '';

  res.writeHead = function (code, headers) {
    console.log(code, req.method, req.url);
    if (code === 304) {
      scriptSrc = '';
      return _writeHead.apply(res, arguments);
    }
    var contentType = this.getHeader('content-type');
    la(check.unemptyString(contentType), 'missing content type for code', code);

    // Strip off the content length since it will change.
    res.removeHeader('Content-Length');
    if (headers) {
      delete headers['content-length'];
    }
    _writeHead.apply(res, arguments);
  };

  res.write = function (chunk) {
    scriptSrc += chunk;
  };

  res.end = function (data) {
    if (data) {
      scriptSrc += data;
    }
    if (scriptSrc) {
      var filename = saveSourceFile(scriptSrc, req.url);
      var instrumented = instrumenter.instrumentSync(scriptSrc, filename);
      instrumented += '\n\n';
      instrumented += setupCoverageSend.toString() + '\n';
      instrumented += 'setupCoverageSend();\n';
      _write.call(res, instrumented);
    }
    _end.call(res);
  };
}

//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});
var getReportUrlPrefix = '__report/';

var reportServer = ecstatic({
  root: savedReportDir,
  baseDir: getReportUrlPrefix
});

function isGetReportRequest(url) {
  return url.indexOf(getReportUrlPrefix) === 1;
}

//
// Create your custom server and just call `proxy.web()` to proxy
// a web request to the target passed in the options
// also you can use `proxy.ws()` to proxy a websockets request
//
var server = http.createServer(function (req, res) {
  // You can define here your custom logic to handle the request
  // and then proxy the request.

  if (req.method === 'GET' && isGetReportRequest(req.url)) {
    console.log('coverage report', req.url);
    reportServer(req, res);
  } else if (req.method === 'GET' && req.url === '/__reset') {
    resetCoverage();
    res.writeHead(200);
    res.end();
  } else if (req.method === 'POST' && req.url === '/__coverage') {
    console.log('received coverage info');
    var str = '';
    req.on('data', function (chunk) {
      str += chunk;
    });
    req.on('end', function () {
      var coverage = JSON.parse(str);
      var combined = combineCoverage(coverage);
      writeCoverageReports(combined);
    });
    res.writeHead(200);
    res.end();
  } else {
    console.log('proxy', req.method, req.url);
    proxy.web(req, res, { target: program.target });
  }
});

proxy.on('proxyRes', function (proxyRes, req, res) {
  // console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
  if (shouldBeInstrumented(req.url)) {
    console.log('will instrument', req.url);
    prepareResponseSelectors(proxyRes, req, res);
  }
});

console.log(pkg.name, 'listening on port', program.port);
server.listen(program.port);
<|endoftext|>


<commit_before>
var Promise = require('native-or-bluebird')
var exec = require('child_process').exec
var mkdirpSync = require('mkdirp').sync
var mkdirp = require('mkdirp-then')
var rimraf = require('rimraf-then')
var path = require('path')
var fs = require('mz/fs')
var cp = require('fs-cp')
var ms = require('ms')

var tmpdir = require('os').tmpdir()

module.exports = Cache

function Cache(name, options) {
  if (!(this instanceof Cache)) return new Cache(name, options)

  options = options || {}
  if (typeof name === 'object') {
    options = name
    name = null
  }

  var folder = this.tmpdir = path.join(tmpdir, 'fs-lru-cache', name || random())
  mkdirpSync(this.tmpdir)

  var maxage = options.maxage || options.maxAge || '30m'
  if (typeof maxage === 'string') maxage = ms(maxage)
  var interval = options.interval || '30m'
  if (typeof interval === 'string') interval = ms(interval)
  // in minutes
  maxage = Math.round(maxage / 1000 / 1000)

  this.interval_id = setInterval(cleanup)
  cleanup()
  function cleanup() {
    exec('find "' + folder
      + '" -mmin +' + maxage
      + ' -type f -delete;', function (err) {
      if (err) console.error(err.stack)
    })
  }
}

/**
 * Define custom serializing and deserializing functions.
 */

Cache.prototype._get = identity
Cache.prototype._set = identity

Cache.prototype.defineGetter = function (fn) {
  this._get = fn
}

Cache.prototype.defineSetter = function (fn) {
  this._set = fn
}

/**
 * Get the filename of an _id.
 */

Cache.prototype.filename = function (_id) {
  return path.join(this.tmpdir, _id)
}

/**
 * Set a raw value.
 */

Cache.prototype.set = function (_id, value) {
  var filename = this.filename(_id)
  return Promise.resolve(this._set(value)).then(function (value) {
    return fs.writeFile(filename, value)
  }).then(function () {
    return filename
  })
}

/**
 * Get a raw value.
 */

Cache.prototype.get = function (_id) {
  var self = this
  var filename = this.filename(_id)
  return fs.readFile(filename).then(function (value) {
    update(filename)
    return self._get(value)
  }).catch(noop)
}

/**
 * Check whether the object exists.
 * If it does, update its atime.
 */

Cache.prototype.access = function (_id) {
  var filename = this.filename(_id)
  return fs.stat(filename).then(function () {
    update(filename)
    return filename
  }).catch(noop)
}

/**
 * Move a file to this _id.
 */

Cache.prototype.move = function (_id, source) {
  var filename = this.filename(_id)
  return fs.rename(path.resolve(source), filename).then(function () {
    return filename
  })
}

/**
 * Copy a file or a stream to this _id.
 */

Cache.prototype.copy = function (_id, source) {
  var filename = this.filename(_id)
  return cp(source, filename)
}

/**
 * Clear the entire cache or just a value.
 */

Cache.prototype.clear = function (_id) {
  if (!_id) {
    var tmpdir = this.tmpdir
    return rimraf(tmpdir).then(function () {
      return mkdirp(tmpdir)
    })
  }

  var filename = this.filename(_id)
  return fs.unlink(filename).catch(noop)
}

function update(filename) {
  var date = new Date()
  fs.utimes(filename, date, date).catch(noop)
}

function random() {
  return Math.random().toString(36).slice(2)
}

function identity(x) {
  return x
}

function noop() {}
<commit_msg>use a var<commit_after>
var Promise = require('native-or-bluebird')
var exec = require('child_process').exec
var mkdirpSync = require('mkdirp').sync
var mkdirp = require('mkdirp-then')
var rimraf = require('rimraf-then')
var path = require('path')
var fs = require('mz/fs')
var cp = require('fs-cp')
var ms = require('ms')

var tmpdir = require('os').tmpdir()

module.exports = Cache

function Cache(name, options) {
  if (!(this instanceof Cache)) return new Cache(name, options)

  options = options || {}
  if (typeof name === 'object') {
    options = name
    name = null
  }

  var folder = this.tmpdir = path.join(tmpdir, 'fs-lru-cache', name || random())
  mkdirpSync(folder)

  var maxage = options.maxage || options.maxAge || '30m'
  if (typeof maxage === 'string') maxage = ms(maxage)
  var interval = options.interval || '30m'
  if (typeof interval === 'string') interval = ms(interval)
  // in minutes
  maxage = Math.round(maxage / 1000 / 1000)

  this.interval_id = setInterval(cleanup)
  cleanup()
  function cleanup() {
    exec('find "' + folder
      + '" -mmin +' + maxage
      + ' -type f -delete;', function (err) {
      if (err) console.error(err.stack)
    })
  }
}

/**
 * Define custom serializing and deserializing functions.
 */

Cache.prototype._get = identity
Cache.prototype._set = identity

Cache.prototype.defineGetter = function (fn) {
  this._get = fn
}

Cache.prototype.defineSetter = function (fn) {
  this._set = fn
}

/**
 * Get the filename of an _id.
 */

Cache.prototype.filename = function (_id) {
  return path.join(this.tmpdir, _id)
}

/**
 * Set a raw value.
 */

Cache.prototype.set = function (_id, value) {
  var filename = this.filename(_id)
  return Promise.resolve(this._set(value)).then(function (value) {
    return fs.writeFile(filename, value)
  }).then(function () {
    return filename
  })
}

/**
 * Get a raw value.
 */

Cache.prototype.get = function (_id) {
  var self = this
  var filename = this.filename(_id)
  return fs.readFile(filename).then(function (value) {
    update(filename)
    return self._get(value)
  }).catch(noop)
}

/**
 * Check whether the object exists.
 * If it does, update its atime.
 */

Cache.prototype.access = function (_id) {
  var filename = this.filename(_id)
  return fs.stat(filename).then(function () {
    update(filename)
    return filename
  }).catch(noop)
}

/**
 * Move a file to this _id.
 */

Cache.prototype.move = function (_id, source) {
  var filename = this.filename(_id)
  return fs.rename(path.resolve(source), filename).then(function () {
    return filename
  })
}

/**
 * Copy a file or a stream to this _id.
 */

Cache.prototype.copy = function (_id, source) {
  var filename = this.filename(_id)
  return cp(source, filename)
}

/**
 * Clear the entire cache or just a value.
 */

Cache.prototype.clear = function (_id) {
  if (!_id) {
    var tmpdir = this.tmpdir
    return rimraf(tmpdir).then(function () {
      return mkdirp(tmpdir)
    })
  }

  var filename = this.filename(_id)
  return fs.unlink(filename).catch(noop)
}

function update(filename) {
  var date = new Date()
  fs.utimes(filename, date, date).catch(noop)
}

function random() {
  return Math.random().toString(36).slice(2)
}

function identity(x) {
  return x
}

function noop() {}
<|endoftext|>


<commit_before>var util = require('util'),
    Url = require('url'),
    querystring = require('querystring'),
    _ = require('underscore');

function Rest(base_url) {
  this.base_url = base_url;
  this.parsed_url = Url.parse(base_url, true);
}

CODES = {
  300: 'Multiple Choices',
  301: 'Moved Permanently',
  302: 'Found',
  303: 'See Other',
  304: 'Not Modified',
  305: 'Use Proxy',
  // 306: '',
  307: 'Temporary Redirect',

  400: 'Bad Request',
  401: 'Unauthorized',
  402: 'Payment Required',
  403: 'Forbidden',
  404: 'Not Found',
  405: 'Method Not Allowed',
  406: 'Not Acceptable',
  407: 'Proxy Authentication Required',
  408: 'Request Timeout',
  409: 'Conflict',
  410: 'Gone',
  411: 'Length Required',
  412: 'Precondition Failed',
  413: 'Request Entity Too Large',
  414: 'Request-URI Too Long',
  415: 'Unsupported Media Type',
  416: 'Requested Range Not Satisfiable',
  417: 'Expectation Failed',

  500: 'Internal Server Error',
  501: 'Not Implemented',
  502: 'Bad Gateway',
  503: 'Service Unavailable',
  504: 'Gateway Timeout',
  505: 'HTTP Version Not Supported'
};

Rest.RestError = function(status_code, body) {
  Error.call(this);
  Error.captureStackTrace(this, arguments.callee);
  this.status_code = status_code;
  this.status_type = CODES[status_code] || 'Unknown';
  this.message = status_code + ': ' + this.status_type;
  this.body = body;
  this.name = 'RestError';
};

Rest.RestError.prototype.__proto__ = Error.prototype;

Rest.prototype.debug = false;

// override-able
Rest.prototype.setRequestOptions = function(options, method, params) {
  options.path += method;
  _.extend(options.query, params);
};

// override-able
Rest.prototype.parseResponseBody = function(headers, body) {
  return JSON.parse(body);
};

Rest.prototype._executeRequest = function(options, callback) {
  function createRequestOptions(options) {
    var query = querystring.stringify(options.query);
    return {
      agent: false,
      host: options.host,
      port: options.port,
      method: options.method,
      path: options.path + (query === '' ? '' : '?' + query),
      headers: options.headers
    };
  }

  var body = '';
  var requestOptions = createRequestOptions(options);
  if (options.body) {
    if (typeof(options.body) !== 'string') {
      options.body = querystring.stringify(options.body);
    }
    options.headers['Content-Length'] = options.body.length;
    options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  }

  if (this.debug) {
    console.log(requestOptions);
    console.log(options);
  }
  var req = require(options.protocol.split(':')[0]).request(requestOptions, function(res) {
    res.setEncoding('utf8');
    res.on('data', function(chunk) {
      body += chunk;
    });
    res.on('end', function() {
      callback(null, res, body);
    });
  });
  req.on('error', callback);

  if (options.body) {
    req.write(options.body);
  }

  req.end();
};

Rest.prototype._handleResponse = function(err, res, body, callback) {
  var parsedBody = '';
  try {
    parsedBody = this.parseResponseBody(res.headers, body);
  } catch (e) {
    // ignore this
  }

  if (err) {
    callback(err);
  } else if (res.statusCode !== 200) {
    callback(new Rest.RestError(res.statusCode, parsedBody));
  } else {
    callback(null, parsedBody);
  }
};

Rest.prototype.request = function(httpMethod, method, params, callback) {
  if (typeof(params) === 'function') {
    callback = params;
    params = {};
  }

  var options = {
    protocol: this.parsed_url.protocol,
    host: this.parsed_url.hostname,
    port: this.parsed_url.port || (this.parsed_url.protocol === 'https:' ? 443 : 80),
    method: httpMethod,
    path: this.parsed_url.pathname || '',
    query: this.parsed_url.query,
    headers: {}
  };

  this.setRequestOptions(options, method, params);

  var self = this;
  this._executeRequest(options, function(err, res, body) {
    self._handleResponse(err, res, body, callback);
  });
}

Rest.prototype.get = function(method, params, callback) {
  this.request('GET', method, params, callback);
};

Rest.prototype.post = function(method, params, callback) {
  this.request('POST', method, params, callback);
};

Rest.prototype.put = function(method, params, callback) {
  this.request('PUT', method, params, callback);
};

Rest.prototype.delete = function(method, params, callback) {
  this.request('DELETE', method, params, callback);
};

module.exports = Rest;
<commit_msg>fixed error inheritance chain<commit_after>var util = require('util'),
    Url = require('url'),
    querystring = require('querystring'),
    _ = require('underscore');

function Rest(base_url) {
  this.base_url = base_url;
  this.parsed_url = Url.parse(base_url, true);
}

CODES = {
  300: 'Multiple Choices',
  301: 'Moved Permanently',
  302: 'Found',
  303: 'See Other',
  304: 'Not Modified',
  305: 'Use Proxy',
  // 306: '',
  307: 'Temporary Redirect',

  400: 'Bad Request',
  401: 'Unauthorized',
  402: 'Payment Required',
  403: 'Forbidden',
  404: 'Not Found',
  405: 'Method Not Allowed',
  406: 'Not Acceptable',
  407: 'Proxy Authentication Required',
  408: 'Request Timeout',
  409: 'Conflict',
  410: 'Gone',
  411: 'Length Required',
  412: 'Precondition Failed',
  413: 'Request Entity Too Large',
  414: 'Request-URI Too Long',
  415: 'Unsupported Media Type',
  416: 'Requested Range Not Satisfiable',
  417: 'Expectation Failed',

  500: 'Internal Server Error',
  501: 'Not Implemented',
  502: 'Bad Gateway',
  503: 'Service Unavailable',
  504: 'Gateway Timeout',
  505: 'HTTP Version Not Supported'
};

Rest.RestError = function(status_code, body) {
  Error.call(this);
  Error.captureStackTrace(this, arguments.callee);
  this.status_code = status_code;
  this.status_type = CODES[status_code] || 'Unknown';
  this.message = status_code + ': ' + this.status_type;
  this.body = body;
  this.name = 'RestError';
};

util.inherits(Rest.RestError, Error);

Rest.prototype.debug = false;

// override-able
Rest.prototype.setRequestOptions = function(options, method, params) {
  options.path += method;
  _.extend(options.query, params);
};

// override-able
Rest.prototype.parseResponseBody = function(headers, body) {
  return JSON.parse(body);
};

Rest.prototype._executeRequest = function(options, callback) {
  function createRequestOptions(options) {
    var query = querystring.stringify(options.query);
    return {
      agent: false,
      host: options.host,
      port: options.port,
      method: options.method,
      path: options.path + (query === '' ? '' : '?' + query),
      headers: options.headers
    };
  }

  var body = '';
  var requestOptions = createRequestOptions(options);
  if (options.body) {
    if (typeof(options.body) !== 'string') {
      options.body = querystring.stringify(options.body);
    }
    options.headers['Content-Length'] = options.body.length;
    options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  }

  if (this.debug) {
    console.log(requestOptions);
    console.log(options);
  }
  var req = require(options.protocol.split(':')[0]).request(requestOptions, function(res) {
    res.setEncoding('utf8');
    res.on('data', function(chunk) {
      body += chunk;
    });
    res.on('end', function() {
      callback(null, res, body);
    });
  });
  req.on('error', callback);

  if (options.body) {
    req.write(options.body);
  }

  req.end();
};

Rest.prototype._handleResponse = function(err, res, body, callback) {
  var parsedBody = '';
  try {
    parsedBody = this.parseResponseBody(res.headers, body);
  } catch (e) {
    // ignore this
  }

  if (err) {
    callback(err);
  } else if (res.statusCode !== 200) {
    callback(new Rest.RestError(res.statusCode, parsedBody));
  } else {
    callback(null, parsedBody);
  }
};

Rest.prototype.request = function(httpMethod, method, params, callback) {
  if (typeof(params) === 'function') {
    callback = params;
    params = {};
  }

  var options = {
    protocol: this.parsed_url.protocol,
    host: this.parsed_url.hostname,
    port: this.parsed_url.port || (this.parsed_url.protocol === 'https:' ? 443 : 80),
    method: httpMethod,
    path: this.parsed_url.pathname || '',
    query: this.parsed_url.query,
    headers: {}
  };

  this.setRequestOptions(options, method, params);

  var self = this;
  this._executeRequest(options, function(err, res, body) {
    self._handleResponse(err, res, body, callback);
  });
}

Rest.prototype.get = function(method, params, callback) {
  this.request('GET', method, params, callback);
};

Rest.prototype.post = function(method, params, callback) {
  this.request('POST', method, params, callback);
};

Rest.prototype.put = function(method, params, callback) {
  this.request('PUT', method, params, callback);
};

Rest.prototype.delete = function(method, params, callback) {
  this.request('DELETE', method, params, callback);
};

module.exports = Rest;
<|endoftext|>