<commit_before>var express = require('express')
var router  = express.Router()
// var path    = require('path')
// var debug   = require('debug')('app:' + path.basename(__filename).replace('.js', ''))
var async   = require('async')
var op      = require('object-path')
var mapper  = require('../helpers/mapper')
var helper  = require('../helpers/helper')

function renderProgram(res, year, month, categories) {
    // console.log('Loading "' + path.basename(__filename).replace('.js', '') + '"')
    var all_categories = SDC.get(['local_entities', 'by_class', 'rootCategory'], {})
    if (!categories) {
        categories = Object.keys(all_categories).map( function(key) { return parseInt(key, 10) })
    } else {
        categories = categories.split(',').map(function(eid){return parseInt(eid, 10)})
    }
    categories.sort(function(a,b){return a-b})

    var program_a = {}
    async.each(SDC.get(['local_entities', 'by_class', 'program']), function(entity, callback) {
        var event = mapper.event(entity.id)
        // console.log(JSON.stringify(event, null, 2))
        if (event['start-time']) {

            var pr_categories = op.get(event, ['performance', 'category'], []).map(function(category) { return category.id })
            pr_categories.sort(function(a,b){return a-b})
            // console.log(event.id, categories, '?==', JSON.stringify(pr_categories))

            var intersects = false
            var ai = 0, bi = 0
            while( ai < pr_categories.length && bi < categories.length && !intersects )
            {
                if      (pr_categories[ai] < categories[bi]) { ai = ai + 1 }
                else if (pr_categories[ai] > categories[bi]) { bi = bi + 1 }
                else { intersects = true }
            }

            if (intersects) {
                // console.log(event.id, categories, ' intersects ', JSON.stringify(pr_categories))
            } else {
                // console.log(event.id, categories, ' doesnot intersect ', JSON.stringify(pr_categories))
                return callback()
            }

            if (month - 1 !== new Date(event['start-time']).getUTCMonth()) {
                // console.log(month - 1, '!==', new Date(event['start-time']).getUTCMonth())
                return callback()
            }
            if (parseInt(year, 10) !== new Date(event['start-time']).getUTCFullYear()) {
                // console.log(year, '!==', new Date(event['start-time']).getUTCFullYear())
                return callback()
            }

            var event_date = (event['start-time']).slice(0,10)
            var event_time = (event['start-time']).slice(11,16)
            op.set(event, 'event-date', event_date)
            op.set(event, 'event-time', event_time)
            op.push(program_a, [event_date, event_time], event)
        }
        callback()
    }, function(err) {
        if (err) {
            console.log('Failed to render program.', err)
            callback(err)
            return
        }
        res.render('program', {
            'monthNav': helper.monthNav(year, month),
            'categories': categories,
            'all_categories': all_categories,
            'program': program_a,
            'arraySubtract': helper.arraySubtract,
        })
        res.end()
    })
}

router
    // .get('/', function(req, res, next) {
    .get('/', function(req, res) {
        var year = new Date().getUTCFullYear()
        var month = new Date().getUTCMonth() + 1
        // console.log('Assuming ' + year + '/' + month )
        renderProgram(res, year, month, undefined)
        res.end()
    })
    // .get('/:year/:month/:categories*?', function(req, res, next) {
    .get('/:year/:month/:categories*?', function(req, res) {
        // console.log('Requested "' + req.url + '"' + JSON.stringify(req.params, null, 2))
        renderProgram(res, req.params.year, req.params.month, req.params.categories)
    })

module.exports = router
<commit_msg>map root categories on program page<commit_after>var express = require('express')
var router  = express.Router()
var path    = require('path')
var debug   = require('debug')('app:' + path.basename(__filename).replace('.js', ''))
var async   = require('async')
var op      = require('object-path')
var mapper  = require('../helpers/mapper')
var helper  = require('../helpers/helper')

function renderProgram(res, year, month, categories) {
    // console.log('Loading "' + path.basename(__filename).replace('.js', '') + '"')
    var all_categories = SDC.get(['local_entities', 'by_class', 'rootCategory'], {})
    if (!categories) {
        categories = Object.keys(all_categories).map( function(key) { return parseInt(key, 10) })
    } else {
        categories = categories.split(',').map(function(eid){return parseInt(eid, 10)})
    }
    categories.sort(function(a,b){return a-b})

    var program_a = {}
    async.each(SDC.get(['local_entities', 'by_class', 'program']), function(entity, callback) {
        var event = mapper.event(entity.id)
        // console.log(JSON.stringify(event, null, 2))
        if (event['start-time']) {

            var performance_eid = op.get(event, ['performance', 'id'])
            var perfCatIds = SDC.get(['relationships', performance_eid, 'category'], []).map(function(eId) { return parseInt(eId, 10) })
            // debug('a', perfCatIds, pr_categories)
            perfCatIds.sort(function(a,b){return a-b})
            // debug('ab', perfCatIds, pr_categories)

            var intersects = false
            var ai = 0, bi = 0
            while( ai < perfCatIds.length && bi < categories.length && !intersects )
            {
                if      (perfCatIds[ai] < categories[bi]) { ai = ai + 1 }
                else if (perfCatIds[ai] > categories[bi]) { bi = bi + 1 }
                else { intersects = true }
            }

            if (intersects) {
                // console.log(event.id, categories, ' intersects ', JSON.stringify(perfCatIds))
            } else {
                // console.log(event.id, categories, ' doesnot intersect ', JSON.stringify(perfCatIds))
                return callback()
            }

            if (month - 1 !== new Date(event['start-time']).getUTCMonth()) {
                // console.log(month - 1, '!==', new Date(event['start-time']).getUTCMonth())
                return callback()
            }
            if (parseInt(year, 10) !== new Date(event['start-time']).getUTCFullYear()) {
                // console.log(year, '!==', new Date(event['start-time']).getUTCFullYear())
                return callback()
            }

            var event_date = (event['start-time']).slice(0,10)
            var event_time = (event['start-time']).slice(11,16)
            op.set(event, 'event-date', event_date)
            op.set(event, 'event-time', event_time)
            op.push(program_a, [event_date, event_time], event)
        }
        callback()
    }, function(err) {
        if (err) {
            console.log('Failed to render program.', err)
            callback(err)
            return
        }
        res.render('program', {
            'monthNav': helper.monthNav(year, month),
            'categories': categories,
            'all_categories': all_categories,
            'program': program_a,
            'arraySubtract': helper.arraySubtract,
        })
        res.end()
    })
}

router
    // .get('/', function(req, res, next) {
    .get('/', function(req, res) {
        var year = new Date().getUTCFullYear()
        var month = new Date().getUTCMonth() + 1
        // console.log('Assuming ' + year + '/' + month )
        renderProgram(res, year, month, undefined)
        res.end()
    })
    // .get('/:year/:month/:categories*?', function(req, res, next) {
    .get('/:year/:month/:categories*?', function(req, res) {
        // console.log('Requested "' + req.url + '"' + JSON.stringify(req.params, null, 2))
        renderProgram(res, req.params.year, req.params.month, req.params.categories)
    })

module.exports = router
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var knox = require('knox');
var moniker = require('moniker');
var ejs = require('ejs');
var fs = require('fs');
var path = require('path');
var lynx = require('lynx');
var metrics = new lynx('localhost', 8125);
var dbModels = require('../lib/db-models');

module.exports = function (store, viewsPath, urlManager, makeAPIPublisher, dbconn) {
  var Component = dbModels.get('Component');
  var App = dbModels.get('App');

  var templates = {
    publish: null,
    install: null
  };

  fs.readFile(viewsPath + '/publish.ejs', 'utf8', function (err, publishHTMLData) {
    templates.publish = ejs.compile(publishHTMLData, {
      // for partial include access
      filename: viewsPath + '/publish.ejs'
    });
  });

  fs.readFile(viewsPath + '/install.ejs', 'utf8', function (err, installHTMLData) {
    templates.install = ejs.compile(installHTMLData, {
      // for partial include access
      filename: viewsPath + '/publish.ejs'
    });
  });

  function getUserComponents (req, callback) {
    if (! req.session.email) {
      console.error('Need to be signed in to retrieve components.');
      callback([]);
      return;
    }
    Component.find({author: req.session.email}, function (err, components) {
      if (err){
        console.error('Unable to retrieve components.');
        callback([]);
        return;
      }
      callback(components.map(function (c) {
        return c.url;
      }));
    });
  }

  return {
    publish: function(app) {
      return function(req, res) {

        var folderName = moniker.choose() + '-' + Math.round(Math.random() * 1000);
        var userName = req.session.user.username;
        var installHTMLFilename =  'install';
        var appHTMLFilename = 'app';
        var manifestFilename = 'manifest.webapp';

        var remoteURLPrefix = urlManager.createURLPrefix(folderName);
        var launchPath = urlManager.createLaunchPath(folderName);

        var remoteURLs = {
          install: remoteURLPrefix + installHTMLFilename,
          app: remoteURLPrefix + appHTMLFilename,
          manifest: remoteURLPrefix + manifestFilename
        };

        var inputData = req.body;
        var manifest = inputData.manifest || {};

        function cleanString (str, removeQuotes) {
          str = str.replace(/>/g, '>').replace(/</g, '<');
          if (removeQuotes) {
            str = str.replace(/'/g, '').replace(/"/g, '')
          }
          return str;
        }

        // core appmaker components
        var coreComponents = app.locals.components;
        var appComponents = [
          //... mine the requestHTML for these? ...
        ];

        var remixUrl = encodeURIComponent(encodeURIComponent(remoteURLs.app));
        getUserComponents(req, function (userComponents) {

          var appDescription = inputData.appDescription || "";
          var appName = inputData.name || req.gettext('My App') + ' - ' + folderName;
          var appStr = templates.publish({
            appHTML: inputData.html,
            folderName: folderName,
            appName: appName,
            gettext: req.gettext,
            ceciComponentURL: process.env.ASSET_HOST,
            remixURL: remixUrl,
            bundles: app.locals.bundles,
            components: coreComponents.concat(appComponents),
            userComponents: userComponents,
            manifestUrl: remoteURLs.manifest
          });

          var installStr = templates.install({
            iframeSrc: remoteURLs.app,
            manifestUrl: remoteURLs.manifest,
            gettext: req.gettext,
            appname: appName,
            username: userName,
            description: appDescription,
            webmakerurl: process.env.WEBMAKER_URL || ""
          });

          var manifestJSON = {
            "name": appName,
            "description": appDescription,
            "launch_path": launchPath,
            "developer": {
              "name": "App Maker",
              "url": "https://appmaker.mozillalabs.com/"
            },
            "icons": {
              "60": "/style/icons/icon-60.png",
              "79": "/style/icons/icon-79.png"
            },
            "default_locale": "en",
            "permissions": {
              "audio-capture": {
                "description": "We'd like to use your microphone"
              },
              "video-capture": {
                "description": "We'd like to use your camera"
              }
            }
          };

          var outputFiles = [
            {filename: urlManager.objectPrefix + '/' + folderName + '/' + manifestFilename,
              data: JSON.stringify(manifestJSON),
              // According to https://developer.mozilla.org/en-US/docs/Web/Apps/Manifest#Serving_manifests
              contentType: 'application/x-web-app-manifest+json'},
            {filename: urlManager.objectPrefix + '/' + folderName + '/' + appHTMLFilename,
              data: appStr},
            {filename: urlManager.objectPrefix + '/' + folderName + '/' + installHTMLFilename,
              data: installStr}
          ];

          var filesDone = 0;

          var setObj = {
            'published-date': new Date()
          };

          App.update({
              author: req.session.email,
              name: inputData.name
            }, {
              $set: setObj
            }, {},
            function(err,obj){
              if(err){
                console.error('Error saving published date to database: ' + err);
              }
            }
          );
          outputFiles.forEach(function (description) {

            store.write(description.filename, description.data, function (result) {
              if (200 !== result.statusCode) {
                console.error('Trouble writing ' + description.filename + ' to S3 (' + result.statusCode + ').');
              }
              if (++filesDone === outputFiles.length) {
                res.json({error: null,
                  app: remoteURLs.app,
                  install: remoteURLs.install,
                  manifest: remoteURLs.manifest
                }, 200);
                // Don't wait for the MakeAPI to deliver url to user
                makeAPIPublisher.publish({
                  url: remoteURLs.install,
                  remix: remixUrl,
                  thumbnail: 'http://appmaker.mozillalabs.com/images/mail-man.png',
                  title: appName,
                  appDescription: appDescription,
                  appTags: inputData.appTags || "",
                  email: req.session.email,
                  author: userName,
                  locale: req.localeInfo.lang
                }, function (err, make) {
                  if (err) {
                    console.error(err);
                  }
                });
              }
            }, description.contentType);
          });
          metrics.increment('appmaker.live.app_published');
        });
      };
    }
  };
};
<commit_msg>fixes #1670 Removing the mailman<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var knox = require('knox');
var moniker = require('moniker');
var ejs = require('ejs');
var fs = require('fs');
var path = require('path');
var lynx = require('lynx');
var metrics = new lynx('localhost', 8125);
var dbModels = require('../lib/db-models');

module.exports = function (store, viewsPath, urlManager, makeAPIPublisher, dbconn) {
  var Component = dbModels.get('Component');
  var App = dbModels.get('App');

  var templates = {
    publish: null,
    install: null
  };

  fs.readFile(viewsPath + '/publish.ejs', 'utf8', function (err, publishHTMLData) {
    templates.publish = ejs.compile(publishHTMLData, {
      // for partial include access
      filename: viewsPath + '/publish.ejs'
    });
  });

  fs.readFile(viewsPath + '/install.ejs', 'utf8', function (err, installHTMLData) {
    templates.install = ejs.compile(installHTMLData, {
      // for partial include access
      filename: viewsPath + '/publish.ejs'
    });
  });

  function getUserComponents (req, callback) {
    if (! req.session.email) {
      console.error('Need to be signed in to retrieve components.');
      callback([]);
      return;
    }
    Component.find({author: req.session.email}, function (err, components) {
      if (err){
        console.error('Unable to retrieve components.');
        callback([]);
        return;
      }
      callback(components.map(function (c) {
        return c.url;
      }));
    });
  }

  return {
    publish: function(app) {
      return function(req, res) {

        var folderName = moniker.choose() + '-' + Math.round(Math.random() * 1000);
        var userName = req.session.user.username;
        var installHTMLFilename =  'install';
        var appHTMLFilename = 'app';
        var manifestFilename = 'manifest.webapp';

        var remoteURLPrefix = urlManager.createURLPrefix(folderName);
        var launchPath = urlManager.createLaunchPath(folderName);

        var remoteURLs = {
          install: remoteURLPrefix + installHTMLFilename,
          app: remoteURLPrefix + appHTMLFilename,
          manifest: remoteURLPrefix + manifestFilename
        };

        var inputData = req.body;
        var manifest = inputData.manifest || {};

        function cleanString (str, removeQuotes) {
          str = str.replace(/>/g, '>').replace(/</g, '<');
          if (removeQuotes) {
            str = str.replace(/'/g, '').replace(/"/g, '')
          }
          return str;
        }

        // core appmaker components
        var coreComponents = app.locals.components;
        var appComponents = [
          //... mine the requestHTML for these? ...
        ];

        var remixUrl = encodeURIComponent(encodeURIComponent(remoteURLs.app));
        getUserComponents(req, function (userComponents) {

          var appDescription = inputData.appDescription || "";
          var appName = inputData.name || req.gettext('My App') + ' - ' + folderName;
          var appStr = templates.publish({
            appHTML: inputData.html,
            folderName: folderName,
            appName: appName,
            gettext: req.gettext,
            ceciComponentURL: process.env.ASSET_HOST,
            remixURL: remixUrl,
            bundles: app.locals.bundles,
            components: coreComponents.concat(appComponents),
            userComponents: userComponents,
            manifestUrl: remoteURLs.manifest
          });

          var installStr = templates.install({
            iframeSrc: remoteURLs.app,
            manifestUrl: remoteURLs.manifest,
            gettext: req.gettext,
            appname: appName,
            username: userName,
            description: appDescription,
            webmakerurl: process.env.WEBMAKER_URL || ""
          });

          var manifestJSON = {
            "name": appName,
            "description": appDescription,
            "launch_path": launchPath,
            "developer": {
              "name": "App Maker",
              "url": "https://appmaker.mozillalabs.com/"
            },
            "icons": {
              "60": "/style/icons/icon-60.png",
              "79": "/style/icons/icon-79.png"
            },
            "default_locale": "en",
            "permissions": {
              "audio-capture": {
                "description": "We'd like to use your microphone"
              },
              "video-capture": {
                "description": "We'd like to use your camera"
              }
            }
          };

          var outputFiles = [
            {filename: urlManager.objectPrefix + '/' + folderName + '/' + manifestFilename,
              data: JSON.stringify(manifestJSON),
              // According to https://developer.mozilla.org/en-US/docs/Web/Apps/Manifest#Serving_manifests
              contentType: 'application/x-web-app-manifest+json'},
            {filename: urlManager.objectPrefix + '/' + folderName + '/' + appHTMLFilename,
              data: appStr},
            {filename: urlManager.objectPrefix + '/' + folderName + '/' + installHTMLFilename,
              data: installStr}
          ];

          var filesDone = 0;

          var setObj = {
            'published-date': new Date()
          };

          App.update({
              author: req.session.email,
              name: inputData.name
            }, {
              $set: setObj
            }, {},
            function(err,obj){
              if(err){
                console.error('Error saving published date to database: ' + err);
              }
            }
          );
          outputFiles.forEach(function (description) {

            store.write(description.filename, description.data, function (result) {
              if (200 !== result.statusCode) {
                console.error('Trouble writing ' + description.filename + ' to S3 (' + result.statusCode + ').');
              }
              if (++filesDone === outputFiles.length) {
                res.json({error: null,
                  app: remoteURLs.app,
                  install: remoteURLs.install,
                  manifest: remoteURLs.manifest
                }, 200);
                // Don't wait for the MakeAPI to deliver url to user
                makeAPIPublisher.publish({
                  url: remoteURLs.install,
                  remix: remixUrl,
                  thumbnail: process.env.ASSET_HOST + "/images/app-icon.png",
                  title: appName,
                  appDescription: appDescription,
                  appTags: inputData.appTags || "",
                  email: req.session.email,
                  author: userName,
                  locale: req.localeInfo.lang
                }, function (err, make) {
                  if (err) {
                    console.error(err);
                  }
                });
              }
            }, description.contentType);
          });
          metrics.increment('appmaker.live.app_published');
        });
      };
    }
  };
};
<|endoftext|>


<commit_before>var cluster = require('cluster');
var protein = require('protein');
var router  = require('router');

var METHODS       = 'all get post put head del delete options'.split(' ');
var MIDDLEWARE    = 'json query log body'.split(' ');
var PROXY_PROTEIN = 'fn getter setter'.split(' ');
var SSL_OPTIONS   = 'cert key'.split(' ');

var noop = function() {};
var defunc = function(fn) {
	return {request:fn.request, response:fn.response};
};
var once = function(fn) {
	var ran = false;

	return function(a,b) {
		if (ran) return;
		ran = true;
		fn(a,b);
	};
};
var reduce = function(args, middleware) {
	var fns = [];

	args = Array.prototype.concat.apply([], args).reduce(function(result, arg) {
		(typeof arg === 'function' ? fns : result).push(arg);
		return result;
	}, []);

	if (!fns.length) return args;

	var fn = fns.length === 1 ? fns.pop() : protein().use(fns);

	args.push(!middleware ? fn : function(req, res, next) {
		middleware(req, res, function(err) {
			if (err) return next(err);
			fn(req, res, next);
		});
	});

	return args;
};

var Branch = function(middleware) {
	this.middleware = protein(middleware);
};
var Root = function() {
	var self = this;

	this.servers = [];
	this.middleware = protein();
	this.route = router();
	this.route.head(function(req, res, next) { // experimental
		var end = res.end;

		req.method = 'GET';
		res.write = res.end = function() {
			res.write = res.end = res.destroy = function() {};
			end.call(res);
		};
		self.route(req, res, next);
	});
	this.route.onmount = once(function() {
		if (self.using(self.route)) return;
		self.use(self.route);
	});
	this.on('request', function(req, res) {
		self.emit('middleware');
		self.middleware(req, res);
	});
};

Root.prototype.__proto__ = Branch.prototype.__proto__ = process.EventEmitter.prototype;
Root.prototype.error = function(fn) { // experimental
	var self = this;

	this.once('middleware', function() {
		self.use(function(err, req, res, next) {
			if (!err) return next();
			fn(err, req, res, next);
		});
	});
	return this;
};
Root.prototype.fork = function() {
	var self = this;
	var args = Array.prototype.concat.apply([], arguments);
	var boot = typeof args[args.length-1] === 'object' ? args.pop() : new Root();
	var route = function(req, res) {
		boot.emit('request', req, res);
	};

	args.forEach(function(pattern) {
		var fn = typeof pattern === 'function' && pattern;

		if (!fn) {
			pattern = pattern.match(/^(?:(?:http|https):\/\/)?([^\/:]*)(?:\:\d+)?(.*)$/) || [];

			var host = new RegExp('^'+(pattern[1] || '*').replace(/\./g, '\\.').replace(/^\*$/, '(.+)?').replace(/\*/g, '[^.]+')+'(:|$)', 'i');
			var path = (pattern[2] || '').replace(/\/$/, '').toLowerCase();

			fn = function(req, res, boot, next) {
				if (!host.test(req.headers.host || '')) return next();
				if (req.url.substring(0, path.length).toLowerCase() !== path) return next();

				req.url = ('/'+req.url.substring(path.length)).replace(/^\/\//, '/');
				boot(req, res);
			};
		}

		self.use(function(req, res, next) {
			fn(req, res, route, next);
		});
	});

	return boot.use(defunc(this.middleware));
};
Root.prototype.address = function() {
	return this.servers[0] && this.servers[0].address();
};
Root.prototype.close = function(callback) {
	var running = this.servers.length;
	var self = this;

	this.once('close', callback || noop);
	this.servers.forEach(function(server) {
		server.once('close', function() {
			if (--running) return;
			self.emit('close');
		});
		server.close();
	});
	this.servers = [];
	return this;
};
Root.prototype.listen = function(server, options, callback) {
	if (typeof server === 'function')  return this.listen(null, null, server);
	if (typeof options === 'function') return this.listen(server, null, options);

	var self = this;
	var address = typeof server === 'string' && server.match(/^([\d\.]+)(?::(\d+))$/);
	var bind = address ? parseInt(address[2], 10) || 0 : server;

	callback = callback || noop;
	options = options || {};
	options.host = address && address[1];

	var reading = SSL_OPTIONS.some(function(name) {
		if (!options[name] || Buffer.isBuffer(options[name])) return false;

		require('fs').readFile(options[name], function(err, buf) {
			if (err) return self.emit('error', err);
			options[name] = buf;
			self.listen(server, options, callback);
		});
		return true;
	});

	if (reading) return this;
	if (server === null || typeof server !== 'object') {
		var env = process.env;
		var args = options.host ? [bind, options.host] : [bind];

		server = options.key ? require('https').createServer(options) : require('http').createServer();
		if (!bind && cluster.isWorker) { // HACK - we wanna to force a random port from net by faking us being master
			cluster.isWorker = false;
			process.env = {};
			server.listen.apply(server, args);
			cluster.isWorker = true;
			process.env = env;
		} else {
			server.listen.apply(server, args);
		}
	}

	server.on('listening', function() {
		if (self.servers.push(server) === 1) {
			self.emit('listening');
		}
		self.once('bind', callback);
		self.emit('bind', server.address().port, server);
	});
	server.on('error', function(err) {
		self.emit('error', err);
	});
	server.on('request', function(req, res) {
		self.emit('request', req, res);
	});
	server.on('upgrade', function(req, connection, head) {
		if (!self.listeners('upgrade').length) return connection.destroy();
		self.emit('upgrade', req, connection, head);
	});
	return this;
};

METHODS.forEach(function(method) {
	Root.prototype[method] = function() {
		this.route[method].apply(this.route, reduce(arguments));
		return this;
	};
	Branch.prototype[method] = function() {
		this.emit('mount', method, reduce(arguments, this.middleware));
		return this;
	};
});
[Root, Branch].forEach(function(Proto) {
	Proto.prototype.branch = function(name, fn) {
		if (this[name]) return this[name];

		var self = this;
		var branch = this[name] = new Branch(this.middleware);

		branch.on('mount', function(method, args) {
			self[method].apply(self, args);
		});

		return fn ? branch.use(fn) : branch;
	};
	Proto.prototype.using = function(fn) {
		return this.middleware.using(fn);
	};
	Proto.prototype.use = function(route, fn) {
		if (!fn) return this.use(null, route);
		if (fn instanceof Root) {
			fn.emit('middleware');
			fn.use(defunc(this.middleware));
			fn = fn.middleware;
		}
		this.middleware.use(route, fn);
		return this;
	};
	PROXY_PROTEIN.forEach(function(method) {
		Proto.prototype[method] = function(name, fn) {
			this.middleware[method](name, fn);
			return this;
		};
	});
});

module.exports = function() {
	var app = new Root();

	Array.prototype.concat.apply([], arguments).forEach(function(middleware) {
		if (typeof middleware === 'string') return app.branch(middleware);
		app.use(middleware);
	});

	return app;
};

MIDDLEWARE.forEach(function(name) {
	module.exports[name] = require('./middleware/'+name);
});<commit_msg>better head handling<commit_after>var cluster = require('cluster');
var protein = require('protein');
var router  = require('router');

var METHODS       = 'all get post put head del delete options'.split(' ');
var MIDDLEWARE    = 'json query log body'.split(' ');
var PROXY_PROTEIN = 'fn getter setter'.split(' ');
var SSL_OPTIONS   = 'cert key'.split(' ');

var noop = function() {};
var defunc = function(fn) {
	return {request:fn.request, response:fn.response};
};
var once = function(fn) {
	var ran = false;

	return function(a,b) {
		if (ran) return;
		ran = true;
		fn(a,b);
	};
};
var reduce = function(args, middleware) {
	var fns = [];

	args = Array.prototype.concat.apply([], args).reduce(function(result, arg) {
		(typeof arg === 'function' ? fns : result).push(arg);
		return result;
	}, []);

	if (!fns.length) return args;

	var fn = fns.length === 1 ? fns.pop() : protein().use(fns);

	args.push(!middleware ? fn : function(req, res, next) {
		middleware(req, res, function(err) {
			if (err) return next(err);
			fn(req, res, next);
		});
	});

	return args;
};

var Branch = function(middleware) {
	this.middleware = protein(middleware);
};
var Root = function() {
	var self = this;

	this.servers = [];
	this.middleware = protein();
	this.route = router();
	this.route.head(function(req, res, next) { // experimental
		var end = res.end;

		req.method = 'GET';
		res.end = function() {
			res.write = res.end = res.destroy = noop;
			end.call(res);
		};
		res.write = function() {
			res.end();
			req.emit('close');
		};
		self.route(req, res, next);
	});
	this.route.onmount = once(function() {
		if (self.using(self.route)) return;
		self.use(self.route);
	});
	this.on('request', function(req, res) {
		self.emit('middleware');
		self.middleware(req, res);
	});
};

Root.prototype.__proto__ = Branch.prototype.__proto__ = process.EventEmitter.prototype;
Root.prototype.error = function(fn) { // experimental
	var self = this;

	this.once('middleware', function() {
		self.use(function(err, req, res, next) {
			if (!err) return next();
			fn(err, req, res, next);
		});
	});
	return this;
};
Root.prototype.fork = function() {
	var self = this;
	var args = Array.prototype.concat.apply([], arguments);
	var boot = typeof args[args.length-1] === 'object' ? args.pop() : new Root();
	var route = function(req, res) {
		boot.emit('request', req, res);
	};

	args.forEach(function(pattern) {
		var fn = typeof pattern === 'function' && pattern;

		if (!fn) {
			pattern = pattern.match(/^(?:(?:http|https):\/\/)?([^\/:]*)(?:\:\d+)?(.*)$/) || [];

			var host = new RegExp('^'+(pattern[1] || '*').replace(/\./g, '\\.').replace(/^\*$/, '(.+)?').replace(/\*/g, '[^.]+')+'(:|$)', 'i');
			var path = (pattern[2] || '').replace(/\/$/, '').toLowerCase();

			fn = function(req, res, boot, next) {
				if (!host.test(req.headers.host || '')) return next();
				if (req.url.substring(0, path.length).toLowerCase() !== path) return next();

				req.url = ('/'+req.url.substring(path.length)).replace(/^\/\//, '/');
				boot(req, res);
			};
		}

		self.use(function(req, res, next) {
			fn(req, res, route, next);
		});
	});

	return boot.use(defunc(this.middleware));
};
Root.prototype.address = function() {
	return this.servers[0] && this.servers[0].address();
};
Root.prototype.close = function(callback) {
	var running = this.servers.length;
	var self = this;

	this.once('close', callback || noop);
	this.servers.forEach(function(server) {
		server.once('close', function() {
			if (--running) return;
			self.emit('close');
		});
		server.close();
	});
	this.servers = [];
	return this;
};
Root.prototype.listen = function(server, options, callback) {
	if (typeof server === 'function')  return this.listen(null, null, server);
	if (typeof options === 'function') return this.listen(server, null, options);

	var self = this;
	var address = typeof server === 'string' && server.match(/^([\d\.]+)(?::(\d+))$/);
	var bind = address ? parseInt(address[2], 10) || 0 : server;

	callback = callback || noop;
	options = options || {};
	options.host = address && address[1];

	var reading = SSL_OPTIONS.some(function(name) {
		if (!options[name] || Buffer.isBuffer(options[name])) return false;

		require('fs').readFile(options[name], function(err, buf) {
			if (err) return self.emit('error', err);
			options[name] = buf;
			self.listen(server, options, callback);
		});
		return true;
	});

	if (reading) return this;
	if (server === null || typeof server !== 'object') {
		var env = process.env;
		var args = options.host ? [bind, options.host] : [bind];

		server = options.key ? require('https').createServer(options) : require('http').createServer();
		if (!bind && cluster.isWorker) { // HACK - we wanna to force a random port from net by faking us being master
			cluster.isWorker = false;
			process.env = {};
			server.listen.apply(server, args);
			cluster.isWorker = true;
			process.env = env;
		} else {
			server.listen.apply(server, args);
		}
	}

	server.on('listening', function() {
		if (self.servers.push(server) === 1) {
			self.emit('listening');
		}
		self.once('bind', callback);
		self.emit('bind', server.address().port, server);
	});
	server.on('error', function(err) {
		self.emit('error', err);
	});
	server.on('request', function(req, res) {
		self.emit('request', req, res);
	});
	server.on('upgrade', function(req, connection, head) {
		if (!self.listeners('upgrade').length) return connection.destroy();
		self.emit('upgrade', req, connection, head);
	});
	return this;
};

METHODS.forEach(function(method) {
	Root.prototype[method] = function() {
		this.route[method].apply(this.route, reduce(arguments));
		return this;
	};
	Branch.prototype[method] = function() {
		this.emit('mount', method, reduce(arguments, this.middleware));
		return this;
	};
});
[Root, Branch].forEach(function(Proto) {
	Proto.prototype.branch = function(name, fn) {
		if (this[name]) return this[name];

		var self = this;
		var branch = this[name] = new Branch(this.middleware);

		branch.on('mount', function(method, args) {
			self[method].apply(self, args);
		});

		return fn ? branch.use(fn) : branch;
	};
	Proto.prototype.using = function(fn) {
		return this.middleware.using(fn);
	};
	Proto.prototype.use = function(route, fn) {
		if (!fn) return this.use(null, route);
		if (fn instanceof Root) {
			fn.emit('middleware');
			fn.use(defunc(this.middleware));
			fn = fn.middleware;
		}
		this.middleware.use(route, fn);
		return this;
	};
	PROXY_PROTEIN.forEach(function(method) {
		Proto.prototype[method] = function(name, fn) {
			this.middleware[method](name, fn);
			return this;
		};
	});
});

module.exports = function() {
	var app = new Root();

	Array.prototype.concat.apply([], arguments).forEach(function(middleware) {
		if (typeof middleware === 'string') return app.branch(middleware);
		app.use(middleware);
	});

	return app;
};

MIDDLEWARE.forEach(function(name) {
	module.exports[name] = require('./middleware/'+name);
});<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index');
});

// GET items < json list
var mongoose = require('mongoose');
var Item = mongoose.model('Item');
var Comment = mongoose.model('Comment');

router.get('/items', function(req, res, next) {
	Item.find(function(err, items) {
		if(err) { return next(err); }

		res.json(items);
	});
});

// POST items
router.post('/items', function(req, res, next) {
	var item = new Item(req.body);

	item.save(function(err, item) {
		if(err){ return next(err); }

		res.json(item);
	});
});

router.param('item', function(req, res,next, id) {
	var query = Item.findById(id);

	query.exec(function (err, item) {
		if (err) { return next(err); }
		if (!item) { return next(new Error('can\'t find item')); }

		req.item = item;
		return next();
	});
});

router.get('/items/:item', function(req, res) {
	res.json(req.item);
});

router.put('/items/:item/upvote', function(req, res, next) {
	req.item.upvote(function(err, post) {
		if (err) { return next(err); }

		res.json(post);
	});
});

module.exports = router;

<commit_msg>added comment route<commit_after>var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index');
});

// GET items < json list
var mongoose = require('mongoose');
var Item = mongoose.model('Item');
var Comment = mongoose.model('Comment');

router.get('/items', function(req, res, next) {
	Item.find(function(err, items) {
		if(err) { return next(err); }

		res.json(items);
	});
});

// POST items
router.post('/items', function(req, res, next) {
	var item = new Item(req.body);

	item.save(function(err, item) {
		if(err){ return next(err); }

		res.json(item);
	});
});

// Post comments on items
router.post('/items/:item/comments', function(req, res, next) {
	var comment = new Comment(req.body);
	comment.item = req.item;

	comment.save(function(err, comment) {
		if (err) { return next(err); }

		req.item.comments.push(comment);
		req.item.save(function(err, item) {
			if(err) { return next(err); }

			res.json(comment);
		});
	});
});

router.param('item', function(req, res,next, id) {
	var query = Item.findById(id);

	query.exec(function (err, item) {
		if (err) { return next(err); }
		if (!item) { return next(new Error('can\'t find item')); }

		req.item = item;
		return next();
	});
});

router.get('/items/:item', function(req, res) {
	res.json(req.item);
});

router.put('/items/:item/upvote', function(req, res, next) {
	req.item.upvote(function(err, post) {
		if (err) { return next(err); }

		res.json(post);
	});
});

module.exports = router;

<|endoftext|>


<commit_before>'use strict';

const log = require('../lib/logger');
const express = require('express');
const router = express.Router();
const cel = require('connect-ensure-login');
const mongoose = require('mongoose');

const dbTeam = require('../lib/db/Team');

const Team = mongoose.model('Team');
const User = mongoose.model('User');
const TeamUser = mongoose.model('TeamUser');

module.exports = router;

router.get('/',cel.ensureLoggedIn('/login'), async function (req, res, next) {
    const teamId = req.query.id;
    const cmd = req.query.cmd;

    if (!teamId) res.redirect('/profile');

    console.log("/team - get");
    console.log(req.query);
    var ret = true;
    var r = {result:"error", status:200};
    switch (cmd){
        case 'getTeamCoaches':
            console.log('Going to get team coaches');
            const tc = await dbTeam.getTeamCoaches(req.user.id, teamId);
            r.result = "ok";
            r.list = tc;
            break;

        case 'getTeamMembers':
            console.log('Going to get team members');
            const tm = await dbTeam.getTeamMembers(req.user.id, teamId);
            r.result = "ok";
            r.list = tm;
            break;

        case 'getAdrDetails':
            console.log('Going to get team address details');
            const tad = await dbTeam.getTeamDetails(req.user.id, teamId);
            r.result = "ok";
            r.details = tad;
            break;

        case 'getData':
            console.log('Going to get team details');
            const td = await dbTeam.getTeamDetails(req.user.id, teamId);
            r.result = 'ok';
            r.team = td;
            break;

        default:
            let t;
            if (cmd)
                console.log('cmd=unknown');

            try {
                t = await dbTeam.getTeamDetails(req.user.id, teamId);
            } catch (err) {
                console.log('team not found id=', teamId);
            }

            if (t) {
                console.log("rendering team", t);
                //console.log("team event", t.registeredOn, t.eventName);
                return res.render('team', {team: t, user: {id: req.user.id, name: req.user.username}});
            } else {
                if (!cmd)
                    return res.render('error',{message:"Tím nebol nájdený", error:{status:''}});
            }
            break;
    }
    res.json(r);
    res.end();

});

router.post('/', cel.ensureLoggedIn('/login'), async function (req, res, next) {
    console.log("/team - post");
    console.log(req.body);
    var ret = true;
    var r = {result:"error", status:200};
    switch (req.body.cmd){

        case 'saveAdrDetails':
            console.log('Going to save team address details');
            try {
                let doc = {};
                let data = JSON.parse(req.body.data);
                switch(req.body.type){
                    case 'billing':
                        doc.billingContact = {};
                        doc.billingAdr = {};
                        doc.billingOrg = {};
                        formatTeamDoc(data, doc.billingOrg, doc.billingAdr, doc.billingContact);
                        break;
                    case 'shipping':
                        doc.shippingContact = {};
                        doc.shippingAdr = {};
                        doc.shippingOrg = {};
                        formatTeamDoc(data, doc.shippingOrg, doc.shippingAdr, doc.shippingContact);
                        break;
                }
                console.log("DOCUMENT",doc);
                const nd = await dbTeam.saveTeamDetails(req.user.id, req.body.teamId, doc);
                r.result = "ok";
            } catch (err) {
                r.message = err.message;
                console.log(err);
            }
            break;

        case 'createTeamMember':
            let memberName = req.body.name;
            console.log('Going to create member: ', memberName);
            try {

                let m = await User.create({fullName:req.body.name, email:req.body.email, dateOfBirth:req.body.dob});
                console.log("Member created", m.fullName, m.id);
                let mt = await TeamUser.create({userId:m.id, teamId:req.body.teamId, role:'member'});
                r.result = "ok";
                r.memberId = m.id;

            } catch (err) {
                r.message = err.message;
                console.log(err);
            }
            break;
        case 'removeTeamMember':
            console.log('Going to remove member: ', req.body.memberId, "from team", req.body.teamId);
            try{
                let conf = await TeamUser.deleteOne({"userId":req.body.memberId, "teamId":req.body.teamId});
                if (conf.deletedCount > 0) {
                    console.log('Member removed', req.body.memberId);
                    r.result = "ok"
                }
            } catch(err) {
                r.message = err.message;
                console.log(err);
            }
            break;

        default:
            console.log('cmd=unknown');
            break;
    }
    res.json(r);
    res.end();

});

function formatTeamDoc(data, org, adr, con){
    console.log("Formatting team document from posted data");
    console.log("DATA",data);
    org.name = data.orgName;
    org.companyNo = data.compNo;
    org.taxNo = data.taxNo;

    adr.addrLine1 = data.addr1;
    adr.addrLine2 = data.addr2;
    adr.city = data.city;
    adr.postCode = data.postCode;

    con.name = data.conName;
    con.phone = data.conPhone;
    con.email = data.conEmail;
}<commit_msg>removed unnecessary logging<commit_after>'use strict';

const log = require('../lib/logger');
const express = require('express');
const router = express.Router();
const cel = require('connect-ensure-login');
const mongoose = require('mongoose');

const dbTeam = require('../lib/db/Team');

const Team = mongoose.model('Team');
const User = mongoose.model('User');
const TeamUser = mongoose.model('TeamUser');

module.exports = router;

router.get('/',cel.ensureLoggedIn('/login'), async function (req, res, next) {
    const teamId = req.query.id;
    const cmd = req.query.cmd;

    if (!teamId) res.redirect('/profile');

    console.log("/team - get");
    console.log(req.query);
    var ret = true;
    var r = {result:"error", status:200};
    switch (cmd){
        case 'getTeamCoaches':
            console.log('Going to get team coaches');
            const tc = await dbTeam.getTeamCoaches(req.user.id, teamId);
            r.result = "ok";
            r.list = tc;
            break;

        case 'getTeamMembers':
            console.log('Going to get team members');
            const tm = await dbTeam.getTeamMembers(req.user.id, teamId);
            r.result = "ok";
            r.list = tm;
            break;

        case 'getAdrDetails':
            console.log('Going to get team address details');
            const tad = await dbTeam.getTeamDetails(req.user.id, teamId);
            r.result = "ok";
            r.details = tad;
            break;

        case 'getData':
            console.log('Going to get team details');
            const td = await dbTeam.getTeamDetails(req.user.id, teamId);
            r.result = 'ok';
            r.team = td;
            break;

        default:
            let t;
            if (cmd)
                console.log('cmd=unknown');

            try {
                t = await dbTeam.getTeamDetails(req.user.id, teamId);
            } catch (err) {
                console.log('team not found id=', teamId);
            }

            if (t) {
                //console.log("rendering team", t);
                //console.log("team event", t.registeredOn, t.eventName);
                return res.render('team', {team: t, user: {id: req.user.id, name: req.user.username}});
            } else {
                if (!cmd)
                    return res.render('error',{message:"Tím nebol nájdený", error:{status:''}});
            }
            break;
    }
    res.json(r);
    res.end();

});

router.post('/', cel.ensureLoggedIn('/login'), async function (req, res, next) {
    console.log("/team - post");
    console.log(req.body);
    var ret = true;
    var r = {result:"error", status:200};
    switch (req.body.cmd){

        case 'saveAdrDetails':
            console.log('Going to save team address details');
            try {
                let doc = {};
                let data = JSON.parse(req.body.data);
                switch(req.body.type){
                    case 'billing':
                        doc.billingContact = {};
                        doc.billingAdr = {};
                        doc.billingOrg = {};
                        formatTeamDoc(data, doc.billingOrg, doc.billingAdr, doc.billingContact);
                        break;
                    case 'shipping':
                        doc.shippingContact = {};
                        doc.shippingAdr = {};
                        doc.shippingOrg = {};
                        formatTeamDoc(data, doc.shippingOrg, doc.shippingAdr, doc.shippingContact);
                        break;
                }
                console.log("DOCUMENT",doc);
                const nd = await dbTeam.saveTeamDetails(req.user.id, req.body.teamId, doc);
                r.result = "ok";
            } catch (err) {
                r.message = err.message;
                console.log(err);
            }
            break;

        case 'createTeamMember':
            let memberName = req.body.name;
            console.log('Going to create member: ', memberName);
            try {

                let m = await User.create({fullName:req.body.name, email:req.body.email, dateOfBirth:req.body.dob});
                console.log("Member created", m.fullName, m.id);
                let mt = await TeamUser.create({userId:m.id, teamId:req.body.teamId, role:'member'});
                r.result = "ok";
                r.memberId = m.id;

            } catch (err) {
                r.message = err.message;
                console.log(err);
            }
            break;
        case 'removeTeamMember':
            console.log('Going to remove member: ', req.body.memberId, "from team", req.body.teamId);
            try{
                let conf = await TeamUser.deleteOne({"userId":req.body.memberId, "teamId":req.body.teamId});
                if (conf.deletedCount > 0) {
                    console.log('Member removed', req.body.memberId);
                    r.result = "ok"
                }
            } catch(err) {
                r.message = err.message;
                console.log(err);
            }
            break;

        default:
            console.log('cmd=unknown');
            break;
    }
    res.json(r);
    res.end();

});

function formatTeamDoc(data, org, adr, con){
    console.log("Formatting team document from posted data");
    console.log("DATA",data);
    org.name = data.orgName;
    org.companyNo = data.compNo;
    org.taxNo = data.taxNo;

    adr.addrLine1 = data.addr1;
    adr.addrLine2 = data.addr2;
    adr.city = data.city;
    adr.postCode = data.postCode;

    con.name = data.conName;
    con.phone = data.conPhone;
    con.email = data.conEmail;
}<|endoftext|>


<commit_before>/*jslint bitwise: true, node: true */
'use strict';

var Discord = require("discord.js");
var Rcon = require("rcon");
var express = require("express");
var app = express();
var http = require("http").Server(app);
var c = require("./config.json");
var debug = c.DEBUG;
var shulker = new Discord.Client();

var client = new Rcon(c.MINECRAFT_SERVER_RCON_IP, c.MINECRAFT_SERVER_RCON_PORT, c.MINECRAFT_SERVER_RCON_PASSWORD);

client.on("auth", function() {
    console.log("[INFO] Authenticated with " + c.MINECRAFT_SERVER_RCON_IP + ":" + c.MINECRAFT_SERVER_RCON_PORT);
}).on("response", function(str) {
    if (debug && str) {
        console.log("[DEBUG] Got response: " + str);
    }
}).on("end", function() {
    console.log("[INFO] Rcon closed!");
}).on("error", function() {
    client.disconnect();
    setTimeout(function() {
        client.connect();
    }, c.RCON_RECONNECT_DELAY * 1000);
});

client.connect();

app.use(function(request, response, next) {
    request.rawBody = "";
    request.setEncoding("utf8");

    request.on("data", function(chunk) {
        request.rawBody += chunk;
    });

    request.on("end", function() {
        next();
    });
});

shulker.on("ready", function() {
    var channel = shulker.channels.get("name", c.DISCORD_CHANNEL).id;
    app.post(c.WEBHOOK, function(request, response) {
        var body = request.rawBody;
        console.log("[INFO] Recieved " + body);
        var re = new RegExp(c.REGEX_MATCH_CHAT_MC);
        var ignored = new RegExp(c.REGEX_IGNORED_CHAT);
        if (!ignored.test(body)) {
            var bodymatch = body.match(re);
            if (debug) {
                console.log("[DEBUG] Username: " + bodymatch[1]);
                console.log("[DEBUG] Text: " + bodymatch[2]);
            }
            var message = "**" + bodymatch[1] + "**: " + bodymatch[2];
            shulker.channels.get("id", channel).sendMessage(message);
        }
        response.send("");
    });
});

shulker.on("message", function(message) {
    if (message.author.id !== shulker.user.id) {
        var data = {
            text: "<" + message.author.username + "> " + message.content
        };
        client.send('tellraw @a ["",' + JSON.stringify(data) + ']');
    }
});

shulker.login(c.DISCORD_EMAIL, c.DISCORD_PASSWORD);

var ipaddress = process.env.OPENSHIFT_NODEJS_IP || process.env.IP || "127.0.0.1";
var serverport = process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || c.PORT;
if (process.env.OPENSHIFT_NODEJS_IP !== undefined) {
    http.listen(serverport, ipaddress, function() {
        console.log("[INFO] Bot listening on *:" + serverport);
    });
} else {
    http.listen(serverport, function() {
        console.log("[INFO] Bot listening on *:" + c.PORT);
    });
}
<commit_msg>Only have one RCON reconnect at the same time<commit_after>/*jslint bitwise: true, node: true */
'use strict';

var Discord = require("discord.js");
var Rcon = require("rcon");
var express = require("express");
var app = express();
var http = require("http").Server(app);
var c = require("./config.json");
var debug = c.DEBUG;
var shulker = new Discord.Client();

var client = new Rcon(c.MINECRAFT_SERVER_RCON_IP, c.MINECRAFT_SERVER_RCON_PORT, c.MINECRAFT_SERVER_RCON_PASSWORD);
var rconTimeout;

client.on("auth", function() {
    console.log("[INFO] Authenticated with " + c.MINECRAFT_SERVER_RCON_IP + ":" + c.MINECRAFT_SERVER_RCON_PORT);
}).on("response", function(str) {
    if (debug && str) {
        console.log("[DEBUG] Got response: " + str);
    }
}).on("end", function() {
    console.log("[INFO] Rcon closed!");
}).on("error", function() {
    if (typeof rconTimeout === 'undefined') {
        client.disconnect();
        rconTimeout = setTimeout(function() {
            client.connect();
            rconTimeout = undefined;
        }, c.RCON_RECONNECT_DELAY * 1000);
    }
});

client.connect();

app.use(function(request, response, next) {
    request.rawBody = "";
    request.setEncoding("utf8");

    request.on("data", function(chunk) {
        request.rawBody += chunk;
    });

    request.on("end", function() {
        next();
    });
});

shulker.on("ready", function() {
    var channel = shulker.channels.get("name", c.DISCORD_CHANNEL).id;
    app.post(c.WEBHOOK, function(request, response) {
        var body = request.rawBody;
        console.log("[INFO] Recieved " + body);
        var re = new RegExp(c.REGEX_MATCH_CHAT_MC);
        var ignored = new RegExp(c.REGEX_IGNORED_CHAT);
        if (!ignored.test(body)) {
            var bodymatch = body.match(re);
            if (debug) {
                console.log("[DEBUG] Username: " + bodymatch[1]);
                console.log("[DEBUG] Text: " + bodymatch[2]);
            }
            var message = "**" + bodymatch[1] + "**: " + bodymatch[2];
            shulker.channels.get("id", channel).sendMessage(message);
        }
        response.send("");
    });
});

shulker.on("message", function(message) {
    if (message.author.id !== shulker.user.id) {
        var data = {
            text: "<" + message.author.username + "> " + message.content
        };
        client.send('tellraw @a ["",' + JSON.stringify(data) + ']');
    }
});

shulker.login(c.DISCORD_EMAIL, c.DISCORD_PASSWORD);

var ipaddress = process.env.OPENSHIFT_NODEJS_IP || process.env.IP || "127.0.0.1";
var serverport = process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || c.PORT;
if (process.env.OPENSHIFT_NODEJS_IP !== undefined) {
    http.listen(serverport, ipaddress, function() {
        console.log("[INFO] Bot listening on *:" + serverport);
    });
} else {
    http.listen(serverport, function() {
        console.log("[INFO] Bot listening on *:" + c.PORT);
    });
}
<|endoftext|>


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

var app = module.exports = express();

var MsgCrypt = require('wechat-crypto');
var config = require('config');

/**
 * 过滤推送数据
 * 参加 http://docs.sensoro.com/cloud/webhook.html 推送数据格式。
 */

function purifyWebhooksData (data) {
  var results = {};
  Device.PROPERTIES.forEach(function(property) {
    if (data[property]) results[property] = data[property];
  });

  return results;
}

app.post('/webhooks', function(io, app, req, res) {
  console.log('Echo SENSORO POST Data :: ');
  console.log(req.body);

  if (!req.body.sn || (!req.body.data && !req.body.encryptData)) {
    return res.status(400).json({
      info: 'No sn or data.'
    });
  }

  res.status(200).json({
    message: 'success'
  });

  if (!req.body.data && !req.body.encryptData) {
    return;
  }

  var data = {};
  if (req.body.data) {
    data = purifyWebhooksData(req.body.data);
  }

  if (req.body.encryptData) {
    var crypter = new MsgCrypt(config.appSecret, config.appKey, config.appId);
    var decryptData = crypter.decrypt(req.body.encryptData).message; //加密需要发送的数据部分
    if (!decryptData.id) {
      return;
    }

    data = purifyWebhooksData(JSON.parse(decryptData));
  }

  Device.findOneAndUpdate({
    sn: req.body.sn
  }, {
    $set: {
      sensorData: data,
      updatedTime: new Date()
    }
  }, {
    upsert: true
  }).exec(function(err) {
    if (err) {
      console.error(err);
    }

    var newLog = new Log({
      sn: req.body.sn,
      events: 'sensor-update',
      sensor: data
    });

    newLog.save(function(err, log) {
       io.emit('sensor-update', log);
    });
  });
});
<commit_msg>remove unuse code<commit_after>var express = require('express');

var app = module.exports = express();

var MsgCrypt = require('wechat-crypto');
var config = require('config');

/**
 * 过滤推送数据
 * 参加 http://docs.sensoro.com/cloud/webhook.html 推送数据格式。
 */

function purifyWebhooksData (data) {
  var results = {};
  Device.PROPERTIES.forEach(function(property) {
    if (data[property]) results[property] = data[property];
  });

  return results;
}

app.post('/webhooks', function(io, app, req, res) {
  console.log('Echo SENSORO POST Data :: ');
  console.log(req.body);

  if (!req.body.sn || (!req.body.data && !req.body.encryptData)) {
    return res.status(400).json({
      info: 'No sn or data.'
    });
  }

  res.status(200).json({
    message: 'success'
  });

  var data = {};
  if (req.body.data) {
    data = purifyWebhooksData(req.body.data);
  }

  if (req.body.encryptData) {
    var crypter = new MsgCrypt(config.appSecret, config.appKey, config.appId);
    var decryptData = crypter.decrypt(req.body.encryptData).message; //加密需要发送的数据部分
    if (!decryptData.id) {
      return;
    }

    data = purifyWebhooksData(JSON.parse(decryptData));
  }

  Device.findOneAndUpdate({
    sn: req.body.sn
  }, {
    $set: {
      sensorData: data,
      updatedTime: new Date()
    }
  }, {
    upsert: true
  }).exec(function(err) {
    if (err) {
      console.error(err);
    }

    var newLog = new Log({
      sn: req.body.sn,
      events: 'sensor-update',
      sensor: data
    });

    newLog.save(function(err, log) {
       io.emit('sensor-update', log);
    });
  });
});
<|endoftext|>


<commit_before>var path                = require('path');
var commands            = require('./lib/commands');
var red                 = require('chalk').red;
var grey                = require('chalk').grey;
var hasDeprecatedConfig = require('./lib/utilities/detect-deprecated-config');

if (hasDeprecatedConfig()) {
    console.log(red('\n===========================================================================\n'));

    console.log(red('NOTICE TO USERS OF ember-cli-deploy VERSION <= 0.0.6\n\n'));

    console.log(grey('ember-cli/ember-cli-deploy') + red(' will now be using this npm module to host the\n'));
    console.log(red('offial Ember CLI deployment tool.\n\n'));

    console.log(red('Due to the changes being made, you should migrate your project to use the\n'));
    console.log(red('new module now.\n\n'));

    console.log(red('For more information on how to migrate from ') + grey('achambers/ember-cli-deploy') + red(' to ') + grey('ember-cli/ember-cli-deploy') + red(', please go to:\n\n'));

    console.log(red('https://github.com/ember-cli/ember-cli-deploy/blob/master/MIGRATION_STEPS.md'));

    console.log(red('\n===========================================================================\n'));
}

function Deploy() {
  this.name = "ember-cli-deploy"
  return this;
}

Deploy.prototype.includedCommands = function() {
  return commands;
};

Deploy.prototype.blueprintsPath = function() {
  return path.join(__dirname, 'blueprints');
};

Deploy.prototype.included = function(app) {
  var deployEnv  = this._deployEnvSetByDeployCommand();
  var root       = app.project.root;
  var configPath = path.join(root, 'config', 'deploy');
  var config;
  var fingerprint;

  if (deployEnv) {
    config = require(configPath)(deployEnv);

    if (config.fingerprint === false) {
      app.options.fingerprint = {enabled: false};
    } else {
      fingerprint = config.fingerprint || {};
      app.options.fingerprint = app.options.fingerprint || {};

      for (var option in fingerprint) {
        app.options.fingerprint[option] = fingerprint[option];
      }
    }
  }
};

Deploy.prototype._deployEnvSetByDeployCommand = function() {
  return process.env.DEPLOY_ENVIRONMENT;
}

module.exports = Deploy;
<commit_msg>Updated DEPLOY_ENVIRONMENT to DEPLOY_TARGET as this was forgotten which caused a bug with fingerprinting<commit_after>var path                = require('path');
var commands            = require('./lib/commands');
var red                 = require('chalk').red;
var grey                = require('chalk').grey;
var hasDeprecatedConfig = require('./lib/utilities/detect-deprecated-config');

if (hasDeprecatedConfig()) {
    console.log(red('\n===========================================================================\n'));

    console.log(red('NOTICE TO USERS OF ember-cli-deploy VERSION <= 0.0.6\n\n'));

    console.log(grey('ember-cli/ember-cli-deploy') + red(' will now be using this npm module to host the\n'));
    console.log(red('offial Ember CLI deployment tool.\n\n'));

    console.log(red('Due to the changes being made, you should migrate your project to use the\n'));
    console.log(red('new module now.\n\n'));

    console.log(red('For more information on how to migrate from ') + grey('achambers/ember-cli-deploy') + red(' to ') + grey('ember-cli/ember-cli-deploy') + red(', please go to:\n\n'));

    console.log(red('https://github.com/ember-cli/ember-cli-deploy/blob/master/MIGRATION_STEPS.md'));

    console.log(red('\n===========================================================================\n'));
}

function Deploy() {
  this.name = "ember-cli-deploy"
  return this;
}

Deploy.prototype.includedCommands = function() {
  return commands;
};

Deploy.prototype.blueprintsPath = function() {
  return path.join(__dirname, 'blueprints');
};

Deploy.prototype.included = function(app) {
  var deployEnv  = this._deployTargetSetByDeployCommand();
  var root       = app.project.root;
  var configPath = path.join(root, 'config', 'deploy');
  var config;
  var fingerprint;

  if (deployEnv) {
    config = require(configPath)(deployEnv);

    if (config.fingerprint === false) {
      app.options.fingerprint = {enabled: false};
    } else {
      fingerprint = config.fingerprint || {};
      app.options.fingerprint = app.options.fingerprint || {};

      for (var option in fingerprint) {
        app.options.fingerprint[option] = fingerprint[option];
      }
    }
  }
};

Deploy.prototype._deployTargetSetByDeployCommand = function() {
  return process.env.DEPLOY_TARGET;
}

module.exports = Deploy;
<|endoftext|>


<commit_before>var Die=require('./Die'),
    toWords=require('./Words');

/**
 * This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit.
 * For additional samples, visit the Alexa Skills Kit developer documentation at
 * https://developer.amazon.com/appsandservices/solutions/alexa/alexa-skills-kit/getting-started-guide
 */

// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.
exports.handler = function (event, context) {
    try {
        console.log("event.session.application.applicationId=" + event.session.application.applicationId);

        /**
         * Uncomment this if statement and populate with your skill's application ID to
         * prevent someone else from configuring a skill that sends requests to this function.
         */

        if (event.session.application.applicationId !== "amzn1.echo-sdk-ams.app.f8484ead-bd05-45f6-9a0e-416e5760031c") {
             console.log("application id %s", event.session.application.applicationId);
             context.fail("Invalid Application ID");
         }

        if (event.request.type === "LaunchRequest") {
            onLaunch(event.request,
                     event.session,
                     function callback(sessionAttributes, speechletResponse) {
                        context.succeed(buildResponse(sessionAttributes, speechletResponse));
                     });
        }  else if (event.request.type === "IntentRequest") {
            onIntent(event.request,
                     event.session,
                     function callback(sessionAttributes, speechletResponse) {
                         context.succeed(buildResponse(sessionAttributes, speechletResponse));
                     });
        } else if (event.request.type === "SessionEndedRequest") {
            onSessionEnded(event.request, event.session);
            context.succeed();
        }
    } catch (e) {
        context.fail("Exception: " + e);
    }
};

/**
 * Called when the user launches the skill without specifying what they want.
 */
function onLaunch(launchRequest, session, callback) {
    console.log("onLaunch requestId=" + launchRequest.requestId
                + ", sessionId=" + session.sessionId);

    // Dispatch to your skill's launch.
    getWelcomeResponse(callback);
}

/**
 * Called when the user specifies an intent for this skill.
 */
function onIntent(intentRequest, session, callback) {
    console.log("onIntent requestId=" + intentRequest.requestId
                + ", sessionId=" + session.sessionId);

    var intent = intentRequest.intent,
        intentName = intentRequest.intent.name;

    // Dispatch to your skill's intent handlers
    console.log("rolling");
    if ("Roll" === intentName) {
        Roll(intent, session, callback);
    } else {
        throw "Invalid intent";
    }
}

// --------------- Functions that control the skill's behavior -----------------------

function getWelcomeResponse(callback) {
    // If we wanted to initialize the session to have some attributes we could add those here.
    var sessionAttributes = {};
    var cardTitle = "Welcome";
    var speechOutput = "Welcome to Dicey, "
                + "Please tell me what you want rolled, ";
    // If the user either does not reply to the welcome message or says something that is not
    // understood, they will be prompted again with this text.
    var repromptText = "Please tell me what you want rolled by saying, "
                + "roll three d six minus one";
    var shouldEndSession = true;

    callback(sessionAttributes,
             buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}

/**
 * Sets the color in the session and prepares the speech to reply to the user.
 */
function Roll(intent, session, callback) {
    var cardTitle = intent.name,
        diceToRollSlot = intent.slots.Dice,
        diceToRoll = "",
        repromptText = "",
        sessionAttributes = {},
        shouldEndSession = true,
        speechOutput = "";
console.log("diceToRoll %s",intent.slots.Dice );
    if (diceToRollSlot) {
        diceToRoll = diceToRollSlot;
        // parse the request and roll dice
        console.log("diceToRoll %s", diceToRoll);
        speechOutput = toWords(doRoll(diceToRoll));
        repromptText = "You can ask me to roll dice by saying, roll three d six";
    } else {
        speechOutput = "I'm not sure what you want me to roll, please try again";
        repromptText = "I'm not sure what you want me to roll, You can ask me "
                + "to roll dice by saying, roll three d six";
    }

    callback(sessionAttributes,
             buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}

var doRoll=function(words) {
    var operands=[], operator, d,
        currentWord=words.shift();
    while( currentWord ) {
        switch(true) {
            case currentWord.match(/[\d]+d[\d]+/)!=null:
                d=new Die();
                var rollResult=d.roll(currentWord);
                operands.push( rollResult.sum );
                if( operands.length > 1) {
                    doOperator(operator, operands);
                }
                break;
            case currentWord.match(/[\d]+/)!=null:
                operands.push(parseInt(currentWord));
                if( operands.length > 1) {
                    doOperator(operator, operands);
                }
                break;
            case currentWord==="+":
            case currentWord==="plus":
                operator="+";
                break;
            case currentWord==="-":
            case currentWord==='minus':
                operator="-";
                break;
        }
        currentWord=words.shift();
    }

    return operands[0];
}

// --------------- Helpers that build all of the responses -----------------------

function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
    return {
        outputSpeech: {
            type: "PlainText",
            text: output
        },
        card: {
            type: "Simple",
            title: "SessionSpeechlet - " + title,
            content: "SessionSpeechlet - " + output
        },
        reprompt: {
            outputSpeech: {
                type: "PlainText",
                text: repromptText
            }
        },
        shouldEndSession: shouldEndSession
    }
}

function buildResponse(sessionAttributes, speechletResponse) {
    return {
        version: "1.0",
        sessionAttributes: sessionAttributes,
        response: speechletResponse
    }
}<commit_msg>refactored to expect two slots<commit_after>var Die=require('./Die'),
    toWords=require('./Words'),
    util=require('util');

/**
 * This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit.
 * For additional samples, visit the Alexa Skills Kit developer documentation at
 * https://developer.amazon.com/appsandservices/solutions/alexa/alexa-skills-kit/getting-started-guide
 */

// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.
exports.handler = function (event, context) {
    try {
        console.log("event.session.application.applicationId=" + event.session.application.applicationId);

        /**
         * Uncomment this if statement and populate with your skill's application ID to
         * prevent someone else from configuring a skill that sends requests to this function.
         */

        if (event.session.application.applicationId !== "amzn1.echo-sdk-ams.app.f8484ead-bd05-45f6-9a0e-416e5760031c") {
             console.log("application id %s", event.session.application.applicationId);
             context.fail("Invalid Application ID");
         }

        if (event.request.type === "LaunchRequest") {
            onLaunch(event.request,
                     event.session,
                     function callback(sessionAttributes, speechletResponse) {
                        context.succeed(buildResponse(sessionAttributes, speechletResponse));
                     });
        }  else if (event.request.type === "IntentRequest") {
            onIntent(event.request,
                     event.session,
                     function callback(sessionAttributes, speechletResponse) {
                         context.succeed(buildResponse(sessionAttributes, speechletResponse));
                     });
        } else if (event.request.type === "SessionEndedRequest") {
            onSessionEnded(event.request, event.session);
            context.succeed();
        }
    } catch (e) {
        context.fail("Exception: " + e);
    }
};

/**
 * Called when the user launches the skill without specifying what they want.
 */
function onLaunch(launchRequest, session, callback) {
    console.log("onLaunch requestId=" + launchRequest.requestId
                + ", sessionId=" + session.sessionId);

    // Dispatch to your skill's launch.
    getWelcomeResponse(callback);
}

/**
 * Called when the user specifies an intent for this skill.
 */
function onIntent(intentRequest, session, callback) {
    console.log("onIntent requestId=" + intentRequest.requestId
                + ", sessionId=" + session.sessionId);

    var intent = intentRequest.intent,
        intentName = intentRequest.intent.name;

    // Dispatch to your skill's intent handlers
    console.log("rolling");
    if ("Roll" === intentName) {
        Roll(intent, session, callback);
    } else {
        throw "Invalid intent";
    }
}

// --------------- Functions that control the skill's behavior -----------------------

function getWelcomeResponse(callback) {
    // If we wanted to initialize the session to have some attributes we could add those here.
    var sessionAttributes = {};
    var cardTitle = "Welcome";
    var speechOutput = "Welcome to Dicey, "
                + "Please tell me what you want rolled, ";
    // If the user either does not reply to the welcome message or says something that is not
    // understood, they will be prompted again with this text.
    var repromptText = "Please tell me what you want rolled by saying, "
                + "roll three d six minus one";
    var shouldEndSession = true;

    callback(sessionAttributes,
             buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}

/**
 * Sets the color in the session and prepares the speech to reply to the user.
 */
function Roll(intent, session, callback) {
    var cardTitle = intent.name,
        numDiceToRollSlot = intent.slots.NumDice,
        diceSizeSlot = intent.slots.DiceSize,
        repromptText = "",
        sessionAttributes = {},
        shouldEndSession = true,
        speechOutput = "";

    if (numDiceToRollSlot && diceSizeSlot) {
        // parse the request and roll dice
        console.log("diceToRoll %sd%s", numDiceToRollSlot, diceSizeSlot );
        speechOutput = toWords( doRoll( [util.format("%sd%s", numDiceToRollSlot,diceSizeSlot )] ) );
        repromptText = "You can ask me to roll dice by saying, roll three d six";
    } else {
        speechOutput = "I'm not sure what you want me to roll, please try again. dice to roll equals "
                + numDiceToRollSlot
                + " and dice size equals "
                + diceSizeSlot ;
        repromptText = "I'm not sure what you want me to roll, You can ask me "
                + "to roll dice by saying, roll three d six";
    }

    callback(sessionAttributes,
             buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}

var doRoll=function(words) {
    var operands=[], operator, d,
        currentWord=words.shift();
    while( currentWord ) {
        switch(true) {
            case currentWord.match(/[\d]+d[\d]+/)!=null:
                d=new Die();
                var rollResult=d.roll(currentWord);
                operands.push( rollResult.sum );
                if( operands.length > 1) {
                    doOperator(operator, operands);
                }
                break;
            case currentWord.match(/[\d]+/)!=null:
                operands.push(parseInt(currentWord));
                if( operands.length > 1) {
                    doOperator(operator, operands);
                }
                break;
            case currentWord==="+":
            case currentWord==="plus":
                operator="+";
                break;
            case currentWord==="-":
            case currentWord==='minus':
                operator="-";
                break;
        }
        currentWord=words.shift();
    }

    return operands[0];
}

// --------------- Helpers that build all of the responses -----------------------

function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
    return {
        outputSpeech: {
            type: "PlainText",
            text: output
        },
        card: {
            type: "Simple",
            title: "SessionSpeechlet - " + title,
            content: "SessionSpeechlet - " + output
        },
        reprompt: {
            outputSpeech: {
                type: "PlainText",
                text: repromptText
            }
        },
        shouldEndSession: shouldEndSession
    }
}

function buildResponse(sessionAttributes, speechletResponse) {
    return {
        version: "1.0",
        sessionAttributes: sessionAttributes,
        response: speechletResponse
    }
}<|endoftext|>