Simple express middleware for parsing Inbound Mandrill Webhook events
@Module MandrillWebhookEventParser
181001
function() {
    if (!(this instanceof EventParser)) {
      return new EventParser();
    }

    /**
    * Parses Mandrill Events request. Sets mandrillEvents property on req. Expects body to contain decoded post body mandrill_events parameter. Please see Madrills article  {@link https://mandrill.zendesk.com/hc/en-us/articles/205583207-What-is-the-format-of-inbound-email-webhooks- | What is the format of inbound email webhook }
    * @param { Request } req - Express request
    * @param { object } req.body - request body
    * @param { string } req.body.mandrill_events - JSON String of Mandrill events
    * @param { Response } res - Express response
    */
    var parser = function(req, res, next) {
      if (req.body && req.body.mandrill_events) {
        try {
          req.mandrillEvents = JSON.parse(req.body.mandrill_events);
          next();
        } catch (err) {
          next(err);
        }
      } else {
        next(new Error('No body or body is missing [mandrill_events] property'));
      }
    };

    return parser;
  }
1108922
function registerEndpoint(url, handler) {
        tchannel.register(url, function (req, res, arg2, arg3) {

            self.middlewareStack.run(req, arg2, arg3,
                function(req, arg2, arg3, callback) {
                    handler(arg2, arg3, req.remoteAddr, callback);
                },
                function(req, err, res1, res2) {
                    res.headers.as = 'raw';
                    if (err) {
                        res.sendNotOk(null, JSON.stringify(err));
                    } else {
                        if (res2 && !Buffer.isBuffer(res2)) {
                            res2 = new Buffer(res2);
                        }

                        res.sendOk(res1, res2);
                    }
                });

        });
    }
132645
function fetchWebhook() {
        if($this->webhookID === null) {
            throw new \BadMethodCallException('Unable to fetch webhook from a message that was not posted by a webhook');
        }
        
        return (new \React\Promise\Promise(function (callable $resolve, callable $reject) {
            $this->client->apimanager()->endpoints->webhook->getWebhook($this->webhookID)->done(function ($data) use ($resolve) {
                $webhook = new \CharlotteDunois\Yasmin\Models\Webhook($this->client, $data);
                $resolve($webhook);
            }, $reject);
        }));
    }
1030146
function (options, callbackFn) {
            var Webpage = require('./webpage'),
                Phantom = require('./phantom'),
                self = this,
                streamPosition = 0,

//            //pass proxy to callbackFn
//            callbackFn.call(self, self.proxy);

            //parses a line from phantoms event stream
                parseResponse = function (response) {
                    var parsedEvent;

                    self.options.debug && console.log('buffer :%s'.grey, response);

                    try {
                        parsedEvent = JSON.parse(response);
                    }
                    catch (exception) {
                        console.error(exception.toString().red.bold);
                        console.error('attempted to parse %s', response);
                        return;
                    }

                    var args = parsedEvent.args;
                    args.unshift(parsedEvent.type);

                    self.options.debug && console.log('emitting %s event on %s'.grey, parsedEvent.type, parsedEvent.source);

                    switch (parsedEvent.source) {
                        //phantomJs server module started and is listening or failed
                        case 'phantom' :
                            self.proxy.phantom.emit.apply(self.proxy.phantom, args);
                            break;
                        case 'page' :
                            self.proxy.page.emit.apply(self.proxy.page, args);
                            break;
                        case 'server' :
                            self.proxy.phantom.emit.apply(self.proxy.phantom, args);
                            break;
                        default :
                            throw new Error('unexpected eventsource:' + parsedEvent.source);

                    }

                };

            var spawnNewProcess = function () {
                var spawn = require('child_process').spawn,
                    serverPath = __dirname + '/' + require('path').normalize('./server/index.js');

                var args = translateOptions2Arguments(options);
                args.proxy.unshift(serverPath, JSON.stringify(options));
                var processArgs = args.phantom.concat(args.proxy);

                //spawn new process
                var phantomjs = spawn(options.phantomjsPath,
                    processArgs,
                    {
                        detached:false,
                        stdio:
                            [
                                process.stdin,
                                process.stdout,
                                process.stderr
                            ]
                    });

                //  phantomjs.unref && phantomjs.unref();
            };

            var ensureServerRunning = function () {
                pingServer(options, function (result) {
                    self.options.debug && console.log('pinged server and got back %s', result);

                    if (result) {
                        self.options.debug && console.log('server already running... proxy value %s', JSON.stringify(self.proxy));
                        callbackFn(self.proxy);

                    }
                    else {
                        self.options.debug && console.log('creating a new server, waiting for servercreated event on %s', self.proxy.phantom);

                        self.proxy.phantom.on('serverCreated', function (result) {
                            self.options.debug && console.log('server created callback fired with value:%s'.yellow.bold, result);
                            callbackFn(self.proxy);
                        });

                        spawnNewProcess();
                    }
                });
            };

            //socket io implementation - credit to node-phantom
            var socketio = require('socket.io');
            var http = require('http');
            this.server = http.createServer(function (request, response) {
                response.writeHead(200, {"Content-Type":"text/html"});
                response.end('<html><head><script src="/socket.io/socket.io.js" type="text/javascript"></script><script type="text/javascript">\n\
                    window.onload=function(){\n\
                    var socket = new io.connect("http://" + window.location.hostname);\n\
                    window.socket = socket;\n\
                    };\n\
                    </script></head><body></body></html>');
            }).listen();

            options.clientPort = this.server.address().port;
            var io = socketio.listen(this.server, {'log level':1});

            io.sockets.on('connection', function (socket) {
                options.debug && console.log('connection'.green);
                socket.on('res', function (response) {
                    var data = JSON.stringify(response);
                    options.debug && console.log('response: %s'.green, data);
                    parseResponse(data);
                });
            });

            //create proxy object
            self.proxy = {
                page:new Webpage(options),
                phantom:new Phantom(options),
                end:function (endCallback) {
                    self.end(function () {
                        endCallback&&endCallback(true);
                    });
                }
            };

            ensureServerRunning();
        }
1301141
function createMiddleware(options, urlType) {
  /**
   * Express middleware handling html requests
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   */
  return async (req, res, next) => {
    const { owner } = req.params;
    const repoName = req.params.repo;
    let refName = req.params.ref || 'master';
    let fpath = req.params[0] || '';

    const repPath = resolveRepositoryPath(options, owner, repoName);

    // issue: #53: handle branch names containing '/' (e.g. 'foo/bar')
    const parsed = await determineRefPathName(repPath, `${req.params.ref}/${req.params[0]}`);
    if (parsed) {
      refName = parsed.ref;
      fpath = parsed.pathName;
    }

    // issue #247: lenient handling of redundant leading slashes in path
    while (fpath.length && fpath[0] === '/') {
      // trim leading slash
      fpath = fpath.substr(1);
    }

    // set response content type
    res.header('Content-Type', 'text/html');

    resolveCommit(repPath, refName)
      .then(commitOid => git.readObject({ dir: repPath, oid: commitOid, filepath: fpath })
        .catch(() => null))
      .then((blobOrTree) => {
        if (!blobOrTree) {
          if (!fpath.length && urlType === 'tree') {
            // 'tree' view
            res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<p>tree view not implemented yet.</body></html>`);
          } else {
            res.status(404).send(`not found: ${escape(fpath)}`);
          }
          return;
        }

        const { type } = blobOrTree;
        if (!fpath.length && type === 'tree' && urlType === 'root') {
          // 'root' view
          res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<p>root view not implemented yet.</body></html>`);
        } else if (type === 'tree' && urlType === 'tree') {
          // directory view
          res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<br>path: ${escape(fpath)}<p>directory view not implemented yet.</body></html>`);
        } else if (type === 'blob' && urlType === 'blob') {
          // single file view
          res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<br>path: ${escape(fpath)}<p>file view not implemented yet.</body></html>`);
        } else {
          res.status(404).send(`not found: ${escape(fpath)}`);
        }
      })
      .catch((err) => {
        options.logger.debug(`[htmlHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
        next(err);
      });
  };
}
934523
async def handler(event):
    """"""
    q1 = event.pattern_match.group(1)
    q2 = urllib.parse.quote(q1)
    await asyncio.wait([
        event.delete(),
        event.respond(DOCS.format(q1, q2), reply_to=event.reply_to_msg_id)
    ])
703506
def invoke_webhook_handlers(self):
		

		webhooks.call_handlers(event=self)

		signal = WEBHOOK_SIGNALS.get(self.type)
		if signal:
			return signal.send(sender=Event, event=self)
907701
function runMiddlewareStack(stack, req, res, callback) {
  let index = 0;
  // the middleware layer handover callback
  function next(err) {
    // get next middleware callback from stack
    const handle = stack[index++];
    // if no more layers in stack, invoke done callback and exit recursion
    if (!handle) {
      callback(err);
      return;
    }
    let error = err;
    // call the middleware handler
    try {
      if (err && handle.length === 4) {
        // there is an error and it's an error-handling middleware
        handle(err, req, res, next);
        return;
      } else if (!err && handle.length < 4) {
        // no error and it's a request-handling middleware
        handle(req, res, next);
        return;
      }
    } catch (e) {
      // if new error thrown, replace the error
      error = e;
    }
    // otherwise skip layer
    next(error);
  }
  // start going through middleware stack
  next();
}
924907
function registerDeclarativeRoutes(app, config, routes, serviceLoader, auth, logger) {

    _.forEach(_.keys(routes), function (routePath) {
        //routePath should be of form "<method> path"
        var parts = _.split(routePath, ' ');
        if (parts.length !== 2) {
            return logger.warn('Invalid route path "%s"', routePath);
        }

        var methods = ['get', 'post', 'put', 'delete', 'all'];

        if (!_.includes(methods, parts[0])) {
            return logger.warn('Invalid method "%s" on route "%s"', parts[0], parts[1]);
        }

        var handler = routes[routePath].handler;
        if (!handler) {
            return logger.warn('Missing handler for route "%s"', parts[1]);
        }

        //handler is something like foo.bar where there's a foo.js handler module which exports bar
        var handlerParts = _.split(handler, '.');

        if (handlerParts.length !== 2) {
            return logger.warn('Invalid handler reference "%s"', parts[1]);
        }

        var handlerMod = serviceLoader.getConsumer('handlers', handlerParts[0]);
        if (!handlerMod) {
            return logger.warn('Could not find handler module named "%s".', handlerParts[0]);
        }

        var handlerFunc = handlerMod[handlerParts[1]];
        if (!handlerFunc) {
            return logger.warn('Could not find handler function "%s" for module "%s"',
                handlerParts[1], handlerParts[0]);
        }

        //Some other projects have defined their own auth scheme.
        //As a temporary workaround, we ignore auth if the auth field is using their scheme,
        //which is an object instead of a string or array.
        var middleware = [];
        if (routes[routePath].auth && !_.isPlainObject(routes[routePath].auth)) {
            middleware = auth.getAuthMiddleware(routes[routePath].auth);
        } else if (!routes[routePath].auth) { //at least set up global auth if it's available
            middleware = auth.getAuthMiddleware();
        } else {
            logger.debug('Ignoring auth');
        }

        //Set up custom validator function on the route
        if (routes[routePath].validate) {
            logger.warn('Using experimental validators.  This might change in the future.');
            var expression = routes[routePath].validate;
            middleware.push(auth.validate(expression));
        }

        middleware.push(handlerFunc);

        //register the route and handler function with express
        app[parts[0]].call(app, parts[1], middleware);
    });

}
881525
def _wrap_callback_parse_event(on_data, message):
    
    if message.type == message.DATA:
        if message.data.type == yamcs_pb2.EVENT:
            event = Event(getattr(message.data, 'event'))
            #pylint: disable=protected-access
            on_data(event)
922124
function (req, res) {

      var event = req.stripeEvent;
      var data = event.data.object;

      // takes care of unexpected event types
      var transactionMethod = stripeTransactions[event.type] || stripeTransactions.unhandled;

      transactionMethod(req, data, function (err){
        if ( !err ) {
          return res.send(200);
        }
        console.log('stripe webhook error');
        console.log(event.type);
        console.log(err.stack);
        res.send(500, err);
      });

    }
810847
function handleOpenURL (event) {
  console.tron.log(event.url)
  let splitUrl = event.url.split('/') // ['https:', '', 'domain', 'route', 'params']
  let importantParameters = splitUrl.splice(3) // ['route', 'params']
  if (importantParameters.length === 0) {
    console.tron.log('Sending to home page')
    return null
  }
  if (importantParameters.length === 1) {
    switch (importantParameters[0]) {
      case 'register':
        console.tron.log(`Sending to Register Page`)
        registerScreen()
        break
      default:
        console.tron.warn(`Unhandled deep link: ${event.url}`)
      // default code block
    }
  }
}
732357
function CoreApplication() {
  var preHookList = [];
  var postHookList = [];
  var routers = [];

  /**
   * Method that receive all http requests
   * @param request
   * @param response
   * @returns {Promise}
   */
  this.requestListener = function (request, response) {
    return Promise.resolve()
      .then(postDecode.bind(this, request))
      .then(runHooks.bind(this, request, response, preHookList))
      .then(dispatch.bind(this, request, response))
      .then(runHooks.bind(this, request, response, postHookList))
      .then(endResponse.bind(this, response))
      .catch(this.onError.bind(this, request, response));
  };

  /**
   * Add router to resolve uri
   * @param router
   * @returns {CoreApplication}
   */
  this.addRouter = function (router) {
    routers.push(router);
    return this;
  };

  /**
   * Add hook before calling action
   * @param callableHook
   * @returns {CoreApplication}
   */
  this.addPreHook = function (callableHook) {
    if (typeof callableHook !== 'function') {
      this.error('Post hook is not callable');
    }
    preHookList.push(callableHook);
    return this;
  };

  /**
   * Add hook after calling action
   * @param callableHook
   * @returns {CoreApplication}
   */
  this.addPostHook = function (callableHook) {
    if (typeof callableHook !== 'function') {
      this.error('Post hook is not callable');
    }
    postHookList.push(callableHook);
    return this;
  };

  /**
   * If page not found
   * @param request
   * @param response
   * @param error
   * @returns {CoreApplication}
   */
  this.onPageNotFound = function (request, response, error) {
    console.log(error);
    response.writeHead(404);
    response.end();
    return this;
  };

  /**
   * If an error occured
   * @param request
   * @param response
   * @param error
   * @returns {CoreApplication}
   */
  this.onError = function (request, response, error) {
    console.error(error);
    response.writeHead(503);
    response.end();
    return this;
  };

  return this;

  /**
   * Dispatch request in good action using routers
   * @param request
   * @param response
   * @returns {Promise}
   */
  function dispatch(request, response) {
    return Promise.resolve()
      .then(resolveRouters.bind(this, request))
      .then(callAction.bind(this, request, response));
  }

  /**
   * Resolve uri using routers
   * @param request
   * @returns {Promise}
   */
  function resolveRouters(request) {
    for (var i = 0, l = routers.length; i < l; i++) {
      var callback = routers[i].resolve(request);
      if (null != callback) {
        return Promise.resolve(callback);
      }
    }
    return Promise.reject('Route not defined for "' + request.url + '"');
  }

  /**
   * Call action and method form resolved route
   * @param request
   * @param response
   * @param callback
   * @returns {*}
   */
  function callAction(request, response, callback) {
    if (typeof callback == 'function') {
      return Promive.resolve()
        .then(callback.bind(null, request, response));
    }

    try {
      var Action = require(ACTION_PATH + '/' + callback.action + '.js');
    } catch (error) {
      if (error.message == 'Cannot find module \'' + ACTION_PATH + '/' + callback.action + '.js\'') {
        return Promise.reject('Action ' + callback.action + ' does not exist.')
          .catch(this.onPageNotFound.bind(this, request, response));
      }
      return Promise.reject(error)
        .catch(this.onError.bind(this, request, response));
    }

    var instance = new Action(request, response);
    // Test if method exists
    if (!instance[callback.method]) {
      return Promise.reject(new Error('Method "' + callback.method + '" not found in action "' + callback.action + '"'));
    }

    var promise = Promise.resolve();
    if (instance.init && 'function' == typeof instance.init) {
      promise = promise.then(function () {
        return instance.init();
      });
    }

    promise = promise.then(function () {
      return instance[callback.method].apply(instance, callback.arguments);
    });

    if (instance.onError && 'function' == typeof instance.onError) {
      promise = promise.catch(function (error) {
        return instance.onError.call(instance, error)
      });
    }

    promise = promise.catch(this.onError.bind(this, request, response));

    return promise;
  }

  /**
   * Decode post data and add input into request
   * @param request
   * @returns {Promise}
   */
  function postDecode(request) {
    return new Promise(function promisePostDecode(resolve) {
      var postData = '';
      if (request.method === 'POST') {
        request.on('data', function (chunk) {
          // append the current chunk of data to the fullBody variable
          postData += chunk.toString();
        });

        request.on('end', function () {
          request.body = qs.parse(postData);
          resolve();
        });

      } else {
        resolve();
      }
    });
  }

  /**
   * Run given hooks
   * @param request
   * @param response
   * @param hooks
   * @returns {Promise}
   */
  function runHooks(request, response, hooks) {
    var promise = Promise.resolve();
    for (var i = 0; i < hooks.length; i++) {
      promise = promise.then(hooks[i].bind(this, request, response));
    }
    return promise;
  }

  /**
   * Finalize response
   * @param response
   */
  function endResponse(response) {
    response.end();
  }
}
1305353
function addHandler(handlerType, type, a, b) {
    if (typeof type !== 'string') {
      console.error('Thorin.action: ' + handlerType + ' type ' + type + " of action " + this.name + ' is not a string.');
      return this;
    }
    var item;
    if (type === HANDLER_TYPE.MIDDLEWARE || type === HANDLER_TYPE.AUTHORIZE) {  // we have type, name, fn
      if (typeof a !== 'string' || typeof b !== 'function') {
        console.error('Thorin.action: ' + handlerType + ' middleware "' + a + '" must have syntax: ' + handlerType + '(type, middlewareName, fn) in action ' + this.name);
        return this;
      }
      item = {
        name: a,
        fn: b
      };
    } else {
      item = {};
      if (typeof a === 'function') {
        item.fn = a;
      } else if (typeof a === 'string' && typeof b === 'function') {
        item.name = a;
        item.fn = b;
      }
      if (typeof item.fn !== 'function') {
        console.error('Thorin.action: ' + handlerType + ' "' + type + '" must have syntax: ' + handlerType + '(type, fn) or (type, targetName, fn) in action ' + this.name);
        return this;
      }
    }
    if (typeof this.events[handlerType][type] === 'undefined') {
      this.events[handlerType][type] = [];
    }
    this.events[handlerType][type].push(item);
    return this;
  }
642519
function addParserEvents(parser) {
  parser.onopentag = parser_opentag;
  parser.onclosetag = parser_closetag;
  parser.ontext = parser_text;
  parser.oncdata = parser_cdata;
  parser.oncomment = parser_comment;
  parser.ondoctype = parser_doctype;
  parser.onerror = parser_error;
}
157881
function RequestHooks_process(api) {
        var that = this, route = api.parsedUrl.pathname;
        logger.info('RequestHooks.process:', route);
        return new Promise(function (resolve, reject) {
            var hook;
            try {
                hook = that.get(route);
                logger.info('RequestHooks.hook:', hook);
                if (!!hook) {
                    resolve(hook.func(api));
                } else {
                    resolve(false);
                }
            } catch (e) {
                logger.error('RequestHooks.hook:', {
                    hook: hook,
                    e: e
                });
                reject(new error.HttpError(500, {hook: route}, 'Hook error', e));
            }
        });
    }
950420
def _wrap_callback_parse_link_event(subscription, on_data, message):
    
    if message.type == message.DATA:
        if message.data.type == yamcs_pb2.LINK_EVENT:
            link_message = getattr(message.data, 'linkEvent')
            link_event = LinkEvent(link_message)
            #pylint: disable=protected-access
            subscription._process(link_event)
            if on_data:
                on_data(link_event)