<commit_before>// Copyright 2013 Joyent, Inc.  All rights reserved.
//
// 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 domain = require('domain');
var net = require('net');
var util = require('util');

var assert = require('assert-plus');
var clone = require('clone');
var once = require('once');

var dtrace = require('./dtrace');
var errors = require('./errors');
var RpcCall = require('./call').RpcCall;
var RpcParser = require('./parser').RpcParser;
var RpcReply = require('./reply').RpcReply;

///--- Globals

var slice = Function.prototype.call.bind(Array.prototype.slice);
var sprintf = util.format;

///--- Private Methods
// "this" is bound to an RpcServer

function ifError(n) {
    function _ifError(err) {
        if (err) {
            err._rpc_next = n;
            throw err;
        }
    }

    return (_ifError);
}

function onConnection(c) {
    var log = this.log;
    var parser = new RpcParser({
        log: log
    });
    var self = this;

    c.on('error', function (err) {
        log.error(err, 'connection error occurred');
    });

    parser.on('message', function onRpcMessage(msg) {
        assert.ok(msg, 'parsed rpc object is null');

        var err;
        function return_error() {
            err.xid = msg.xid;
            c.write(err.toBuffer());
        }

        log.trace({
            rpc_call: msg
        }, 'call received');

        if (msg.rpcvers !== 2) {
            err = new errors.RpcMismatchError();
            return_error();
        } else if (msg.prog !== self.program) {
            err = new errors.RpcProgramUnavailableError();
            return_error();
        } else if (self.version.indexOf(msg.vers) === -1) {
            err = new errors.RpcProgramMismatchError();
            err.setVersion(self.version[self.version.length - 1]);
            return_error();
        } else if (!self.rpc_table[msg.proc]) {
            if (msg.proc === 0) { // NULL RPC handler
                msg.incoming = false;
                var _null = new RpcReply(msg);
                _null.pipe(c, {end: false});
                _null.writeHead();
                _null.end();
                msg.incoming = true;
            } else {
                err = new errors.RpcProcedureUnavailableError();
                return_error();
            }
        } else {
            var cfg = self.rpc_table[msg.proc];

            msg.incoming = false;
            var reply = new cfg.reply(msg);
            reply.pipe(c, {end: false});

            msg.incoming = true;
            var call;
            if (cfg.call) {
                call = new cfg.call(msg);
                msg.pipe(call);
            } else {
                call = msg;
            }

            call.connection = c;
            process.nextTick(function () {
                self.emit(cfg.name, call, reply);
            });
        }
    });

    c.pipe(parser);
}

///--- API

// An RPC service is identified by its RPC program number, version
// number, and the transport address where it may be reached.  The
// transport address, in turn, consists of a network address and a
// transport selector.  In the case of a service available over TCP/IP
// or UDP/IP, the network address will be an IP address, and the
// transport selector will be a TCP or UDP port number.

function RpcServer(opts) {
    assert.object(opts, 'options');
    assert.object(opts.log, 'options.log');
    assert.number(opts.program, 'options.program');

    var v = opts.version;
    if (typeof (v) === 'number')
        v = [v];

    assert.arrayOfNumber(v, 'options.version');

    net.Server.call(this, opts);

    this.log = opts.log.child({
        component: 'RpcServer'
    }, true);
    this.name = opts.name || 'RpcServer';
    this.program = opts.program;
    this.rpc_table = {};
    this.saved_handlers = [];
    this.version = v.slice();

    this.on('connection', onConnection.bind(this));
}
util.inherits(RpcServer, net.Server);

RpcServer.prototype.use = function use(chain) {
    if (!Array.isArray(chain))
        chain = [chain];
    assert.arrayOfFunc(chain);

    var self = this;
    chain.forEach(function (c) {
        self.saved_handlers.push(c);
        Object.keys(self.rpc_table).forEach(function (k) {
            self.rpc_table[k].push(c);
        });
    });
};

RpcServer.prototype._mount = function _mount(cfg, chain) {
    assert.object(cfg, 'config');

    if (Array.isArray(chain) && chain.length) {
        if (Array.isArray(chain[0]))
            chain = chain[0];
    }

    assert.arrayOfFunc(chain);

    chain.unshift(cfg);
    this._rpc.apply(this, chain);
};

/**
 * Runs a series of handlers given an RPC procedure.
 *
 * var cfg = {
 *   procedure: 4,           // What RPC procedure
 *   reply: PortmapDumpReply // What Type of Reply instance to create
 * };
 * server._rpc(cfg, function (req, res, next) {
 *   res.addMapping({...}); // procedure specific
 *   res.writeHead();
 *   res.end();
 *   next();
 * });
 */
RpcServer.prototype._rpc = function _rpc(opts) {
    assert.object(opts, 'options');
    assert.string(opts.name, 'options.name');
    assert.number(opts.procedure, 'options.procedure');
    assert.optionalFunc(opts.call, 'options.call');
    assert.func(opts.reply, 'options.reply');

    var args = this.saved_handlers.concat(slice(arguments, 1));
    assert.arrayOfFunc(args, 'handler chain');

    var self = this;

    this.rpc_table[opts.procedure] = {
        name: opts.name,
        procedure: opts.procedure,
        call: opts.call,
        reply: opts.reply,
        chain: args
    };
    this.on(opts.name, function onRpcCall(call, reply) {
        var log = self.log.child({
            procedure: opts.name,
            xid: call.xid
        }, true);

        call.log = log;
        reply.log = log;

        call._rpc_proc_name = opts.name;

        self._run(call, reply, self.rpc_table[opts.procedure].chain);
    });
};

RpcServer.prototype._run = function _run(req, res, chain) {
    var d;
    var err;
    var i = -1;
    var id = req.xid;
    var log = this.log;
    var self = this;

    function fire_rpc() {
        return ([
            self.name,
            req._rpc_proc_name,
            id
        ]);
    }

    function fire_handler() {
        return ([
            self.name,
            req._rpc_proc_name,
            id
        ]);
    }

    function next(arg) {
        var done = false;

        if (arg) {
            if (arg instanceof Error) {
                log.trace(arg, 'next(err=%s)', (arg.name || 'Error'));
                arg.xid = req.xid;
                err = arg;
                req.connection.write(err.toBuffer());
                done = true;
            }
        }

        if (arg === false)
            done = true;

        var h_name;
        // Fire DTrace done for the previous handler.
        if ((i + 1) > 0 && chain[i] && !chain[i]._skip) {
            h_name = chain[i].name || ('handler-' + i);
            dtrace._rpc_probes['handler-done'].fire(function () {
                return ([
                    self.name,
                    req._rpc_proc_name,
                    h_name,
                    id
                ]);
            });
        }

        // Run the next handler up
        if (!done && chain[++i]) {
            if (chain[i]._skip) {
                next();
                return;
            }

            h_name = chain[i].name || ('handler-' + i);
            dtrace._rpc_probes['handler-start'].fire(function () {
                return ([
                    self.name,
                    req._rpc_proc_name,
                    h_name,
                    id
                ]);
            });

            var n = once(next);
            n.ifError = ifError(n);

            if (log.trace()) {
                log.trace({
                    route_name: n,
                    rpc_call: req,
                    rpc_reply: res
                }, '%s: running handler %s', self.name, h_name);
            }
            chain[i].call(self, req, res, n);
            return;
        }

        dtrace._rpc_probes['rpc-done'].fire(fire_rpc);

        self.emit('after', req._rpc_proc_name, req, res, err);
    }

    var n1 = once(next);
    n1.ifError = ifError(n1);

    dtrace._rpc_probes['rpc-start'].fire(fire_rpc);

    d = domain.create();
    d.add(req);
    d.add(res);
    d.on('error', function onError(error) {
        if (error._rpc_next) {
            error._rpc_next(error);
        } else if (self.listeners('uncaughtException').length) {
            self.emit('uncaughtException', req, res, error);
        } else {
            req.connection.destroy();
            self.emit('after', req._rpc_proc_name, req, res, error);
        }
    });

    d.run(n1);
};

RpcServer.prototype.toString = function toString() {
    var fmt = '[object RpcServer <program=%d, version=%d>]';
    return (sprintf(fmt, this.program, this.version));
};

function createServer(opts) {
    return (new RpcServer(opts));
}

///--- Exports

module.exports = {
    RpcServer: RpcServer,
    createServer: createServer
};
<commit_msg>MANTA-1844 nfs client can have more than 10 ops running at once<commit_after>// Copyright 2013 Joyent, Inc.  All rights reserved.
//
// 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 domain = require('domain');
var net = require('net');
var util = require('util');

var assert = require('assert-plus');
var clone = require('clone');
var once = require('once');

var dtrace = require('./dtrace');
var errors = require('./errors');
var RpcCall = require('./call').RpcCall;
var RpcParser = require('./parser').RpcParser;
var RpcReply = require('./reply').RpcReply;

///--- Globals

var slice = Function.prototype.call.bind(Array.prototype.slice);
var sprintf = util.format;

///--- Private Methods
// "this" is bound to an RpcServer

function ifError(n) {
    function _ifError(err) {
        if (err) {
            err._rpc_next = n;
            throw err;
        }
    }

    return (_ifError);
}

function onConnection(c) {
    var log = this.log;
    var parser = new RpcParser({
        log: log
    });
    var self = this;

    // Clients can have many requests running in parallel
    c.setMaxListeners(256);

    c.on('error', function (err) {
        log.error(err, 'connection error occurred');
    });

    parser.on('message', function onRpcMessage(msg) {
        assert.ok(msg, 'parsed rpc object is null');

        var err;
        function return_error() {
            err.xid = msg.xid;
            c.write(err.toBuffer());
        }

        log.trace({
            rpc_call: msg
        }, 'call received');

        if (msg.rpcvers !== 2) {
            err = new errors.RpcMismatchError();
            return_error();
        } else if (msg.prog !== self.program) {
            err = new errors.RpcProgramUnavailableError();
            return_error();
        } else if (self.version.indexOf(msg.vers) === -1) {
            err = new errors.RpcProgramMismatchError();
            err.setVersion(self.version[self.version.length - 1]);
            return_error();
        } else if (!self.rpc_table[msg.proc]) {
            if (msg.proc === 0) { // NULL RPC handler
                msg.incoming = false;
                var _null = new RpcReply(msg);
                _null.pipe(c, {end: false});
                _null.writeHead();
                _null.end();
                msg.incoming = true;
            } else {
                err = new errors.RpcProcedureUnavailableError();
                return_error();
            }
        } else {
            var cfg = self.rpc_table[msg.proc];

            msg.incoming = false;
            var reply = new cfg.reply(msg);
            reply.pipe(c, {end: false});

            msg.incoming = true;
            var call;
            if (cfg.call) {
                call = new cfg.call(msg);
                msg.pipe(call);
            } else {
                call = msg;
            }

            call.connection = c;
            process.nextTick(function () {
                self.emit(cfg.name, call, reply);
            });
        }
    });

    c.pipe(parser);
}

///--- API

// An RPC service is identified by its RPC program number, version
// number, and the transport address where it may be reached.  The
// transport address, in turn, consists of a network address and a
// transport selector.  In the case of a service available over TCP/IP
// or UDP/IP, the network address will be an IP address, and the
// transport selector will be a TCP or UDP port number.

function RpcServer(opts) {
    assert.object(opts, 'options');
    assert.object(opts.log, 'options.log');
    assert.number(opts.program, 'options.program');

    var v = opts.version;
    if (typeof (v) === 'number')
        v = [v];

    assert.arrayOfNumber(v, 'options.version');

    net.Server.call(this, opts);

    this.log = opts.log.child({
        component: 'RpcServer'
    }, true);
    this.name = opts.name || 'RpcServer';
    this.program = opts.program;
    this.rpc_table = {};
    this.saved_handlers = [];
    this.version = v.slice();

    this.on('connection', onConnection.bind(this));
}
util.inherits(RpcServer, net.Server);

RpcServer.prototype.use = function use(chain) {
    if (!Array.isArray(chain))
        chain = [chain];
    assert.arrayOfFunc(chain);

    var self = this;
    chain.forEach(function (c) {
        self.saved_handlers.push(c);
        Object.keys(self.rpc_table).forEach(function (k) {
            self.rpc_table[k].push(c);
        });
    });
};

RpcServer.prototype._mount = function _mount(cfg, chain) {
    assert.object(cfg, 'config');

    if (Array.isArray(chain) && chain.length) {
        if (Array.isArray(chain[0]))
            chain = chain[0];
    }

    assert.arrayOfFunc(chain);

    chain.unshift(cfg);
    this._rpc.apply(this, chain);
};

/**
 * Runs a series of handlers given an RPC procedure.
 *
 * var cfg = {
 *   procedure: 4,           // What RPC procedure
 *   reply: PortmapDumpReply // What Type of Reply instance to create
 * };
 * server._rpc(cfg, function (req, res, next) {
 *   res.addMapping({...}); // procedure specific
 *   res.writeHead();
 *   res.end();
 *   next();
 * });
 */
RpcServer.prototype._rpc = function _rpc(opts) {
    assert.object(opts, 'options');
    assert.string(opts.name, 'options.name');
    assert.number(opts.procedure, 'options.procedure');
    assert.optionalFunc(opts.call, 'options.call');
    assert.func(opts.reply, 'options.reply');

    var args = this.saved_handlers.concat(slice(arguments, 1));
    assert.arrayOfFunc(args, 'handler chain');

    var self = this;

    this.rpc_table[opts.procedure] = {
        name: opts.name,
        procedure: opts.procedure,
        call: opts.call,
        reply: opts.reply,
        chain: args
    };
    this.on(opts.name, function onRpcCall(call, reply) {
        var log = self.log.child({
            procedure: opts.name,
            xid: call.xid
        }, true);

        call.log = log;
        reply.log = log;

        call._rpc_proc_name = opts.name;

        self._run(call, reply, self.rpc_table[opts.procedure].chain);
    });
};

RpcServer.prototype._run = function _run(req, res, chain) {
    var d;
    var err;
    var i = -1;
    var id = req.xid;
    var log = this.log;
    var self = this;

    function fire_rpc() {
        return ([
            self.name,
            req._rpc_proc_name,
            id
        ]);
    }

    function fire_handler() {
        return ([
            self.name,
            req._rpc_proc_name,
            id
        ]);
    }

    function next(arg) {
        var done = false;

        if (arg) {
            if (arg instanceof Error) {
                log.trace(arg, 'next(err=%s)', (arg.name || 'Error'));
                arg.xid = req.xid;
                err = arg;
                req.connection.write(err.toBuffer());
                done = true;
            }
        }

        if (arg === false)
            done = true;

        var h_name;
        // Fire DTrace done for the previous handler.
        if ((i + 1) > 0 && chain[i] && !chain[i]._skip) {
            h_name = chain[i].name || ('handler-' + i);
            dtrace._rpc_probes['handler-done'].fire(function () {
                return ([
                    self.name,
                    req._rpc_proc_name,
                    h_name,
                    id
                ]);
            });
        }

        // Run the next handler up
        if (!done && chain[++i]) {
            if (chain[i]._skip) {
                next();
                return;
            }

            h_name = chain[i].name || ('handler-' + i);
            dtrace._rpc_probes['handler-start'].fire(function () {
                return ([
                    self.name,
                    req._rpc_proc_name,
                    h_name,
                    id
                ]);
            });

            var n = once(next);
            n.ifError = ifError(n);

            if (log.trace()) {
                log.trace({
                    route_name: n,
                    rpc_call: req,
                    rpc_reply: res
                }, '%s: running handler %s', self.name, h_name);
            }
            chain[i].call(self, req, res, n);
            return;
        }

        dtrace._rpc_probes['rpc-done'].fire(fire_rpc);

        self.emit('after', req._rpc_proc_name, req, res, err);
    }

    var n1 = once(next);
    n1.ifError = ifError(n1);

    dtrace._rpc_probes['rpc-start'].fire(fire_rpc);

    d = domain.create();
    d.add(req);
    d.add(res);
    d.on('error', function onError(error) {
        if (error._rpc_next) {
            error._rpc_next(error);
        } else if (self.listeners('uncaughtException').length) {
            self.emit('uncaughtException', req, res, error);
        } else {
            req.connection.destroy();
            self.emit('after', req._rpc_proc_name, req, res, error);
        }
    });

    d.run(n1);
};

RpcServer.prototype.toString = function toString() {
    var fmt = '[object RpcServer <program=%d, version=%d>]';
    return (sprintf(fmt, this.program, this.version));
};

function createServer(opts) {
    return (new RpcServer(opts));
}

///--- Exports

module.exports = {
    RpcServer: RpcServer,
    createServer: createServer
};
<|endoftext|>


<commit_before>'use strict';

function hitGiphyAPI(translationPhrase) {
  gif = null;
  request({
    uri: "http://api.giphy.com/v1/gifs/translate",
    qs: { s: translationPhrase, api_key: GIPHY_API_TOKEN }
  }, function(error, response, body) {
    if (!error && response.statusCode == 200) {
      gif = JSON.parse(body).data.images.fixed_height.url;
    } else {
      console.log("EEEERRRRRROOOOOORRRRRR");
      console.log(response.statusCode);
      console.log(error);
    }
  });
  return gif
}

function shouldTakeAction(text) {
  return /^gifacle\s.*/.test(text);
}

function parseMessage(text) {
  console.log(text)
  phrase = /^gifacle\s(.*)/.exec(text)[1]
  console.log(phrase[0])
  console.log(phrase[1])
  return phrase[1]
}

function gifParty() {
}

function gifTranslate() {
}

function isTextMessage(msg) {
  return msg.message;
}

function callSendAPI(message) {
  request({
    uri: 'https://graph.facebook.com/v2.8/me/messages',
    qs: { access_token: PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: message

  } , function (error, response, body) {
    if (!error && response.statusCode== 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Succesfully sent message with id %s to recipient %s", messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

function sendGif(sendTo, gif) {
  var messageData = {
    recipient: {
      id: sendTo
    },
    message: {
      attachment: {
        type: "image",
        payload: {
          url: gif
        }
      }
    }
  };

  callSendAPI(messageData);
}

function handleTextMessage(msg) {
  var senderID = msg.sender.id;
  var recipientID = msg.recipient.id;
  var timeOfMessage= msg.timestamp;
  var message = msg.message;

  console.log("Received message for user %d and page %d at %d with message: ", senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  var messageText = message.text;

  if (messageText) {
    if (shouldTakeAction(messageText)) {
      phrase = parseMessage(messageText);
      gif = hitGiphyAPI(phrase);
      if (gif != null) {
        sendGif(senderID, gif);
      } else {
        sendTextMessage(senderID, "could not match phrase");
      }
    }
  }
}

function sendTextMessage(sendTo, msg) {
  var messageData = {
    recipient: {
      id: sendTo
    },
    message: {
      text: msg
    }
  };

  callSendAPI(messageData);
}

function verifyRequestSignature(req, res, buf) {
  var signature = req.headers["x-hub-signature"];

  if (!signature) {
    // For testing, let's log an error. In production, you should throw an
    // error.
    console.error("Couldn't validate the signature.");
  } else {
    var elements = signature.split('=');
    var method = elements[0];
    var signatureHash = elements[1];

    var expectedHash = crypto.createHmac('sha1', APP_SECRET)
        .update(buf)
        .digest('hex');

    if (signatureHash != expectedHash) {
      throw new Error("Couldn't validate the request signature.");
    }
  }
}

const bodyParser = require('body-parser')
const express = require('express');
const https = require('https');
const request = require('request');
const crypto = require('crypto');

var app = express();
app.set('port', process.env.PORT || 5000);
app.use(bodyParser.json({ verify: verifyRequestSignature }));
app.use(express.static('public'));

const VALIDATION_TOKEN = process.env.VALIDATION_TOKEN;
const PAGE_ACCESS_TOKEN = process.env.PAGE_ACCESS_TOKEN;
const APP_SECRET = process.env.APP_SECRET;
const GIPHY_API_TOKEN = "dc6zaTOxFJmzC";

if (!VALIDATION_TOKEN) {
  console.error("VALIDATION_TOKEN missing");
  process.exit(1);
}

app.get("/", function(req, res){
  res.send("hello");
})

// Routes
app.get('/webhook', function(req, res) {
  if (req.query['hub.verify_token'] === VALIDATION_TOKEN) {
    console.log("Validating webhook");
    res.status(200).send(req.query['hub.challenge']);
  } else {
    console.error("Failed validation. Make sure the validation tokens match.");
    res.sendStatus(403);
  }
});

app.post('/webhook', function (req, res) {
//  console.log(req)
  var data = req.body;
  console.log(data);

  if (data.object == 'page') {
    data.entry.forEach(function (pageEntry) {
      pageEntry.messaging.forEach(function (msg) {
        if (isTextMessage(msg)) {
          handleTextMessage(msg)
          // ignore others for now
          // TODO: do not ignore
        }
      });
    });
  }
  res.sendStatus(200);
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});
<commit_msg>remeber how js works<commit_after>'use strict';

function hitGiphyAPI(translationPhrase) {
  var gif = null;
  request({
    uri: "http://api.giphy.com/v1/gifs/translate",
    qs: { s: translationPhrase, api_key: GIPHY_API_TOKEN }
  }, function(error, response, body) {
    if (!error && response.statusCode == 200) {
      gif = JSON.parse(body).data.images.fixed_height.url;
    } else {
      console.log("EEEERRRRRROOOOOORRRRRR");
      console.log(response.statusCode);
      console.log(error);
    }
  });
  return gif
}

function shouldTakeAction(text) {
  return /^gifacle\s.*/.test(text);
}

function parseMessage(text) {
  console.log(text)
  var phrase = /^gifacle\s(.*)/.exec(text)[1]
  console.log(phrase[0])
  console.log(phrase[1])
  return phrase[1]
}

function gifParty() {
}

function gifTranslate() {
}

function isTextMessage(msg) {
  return msg.message;
}

function callSendAPI(message) {
  request({
    uri: 'https://graph.facebook.com/v2.8/me/messages',
    qs: { access_token: PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: message

  } , function (error, response, body) {
    if (!error && response.statusCode== 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Succesfully sent message with id %s to recipient %s", messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

function sendGif(sendTo, gif) {
  var messageData = {
    recipient: {
      id: sendTo
    },
    message: {
      attachment: {
        type: "image",
        payload: {
          url: gif
        }
      }
    }
  };

  callSendAPI(messageData);
}

function handleTextMessage(msg) {
  var senderID = msg.sender.id;
  var recipientID = msg.recipient.id;
  var timeOfMessage= msg.timestamp;
  var message = msg.message;

  console.log("Received message for user %d and page %d at %d with message: ", senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  var messageText = message.text;

  if (messageText) {
    if (shouldTakeAction(messageText)) {
      var phrase = parseMessage(messageText);
      var gif = hitGiphyAPI(phrase);
      if (gif != null) {
        sendGif(senderID, gif);
      } else {
        sendTextMessage(senderID, "could not match phrase");
      }
    }
  }
}

function sendTextMessage(sendTo, msg) {
  var messageData = {
    recipient: {
      id: sendTo
    },
    message: {
      text: msg
    }
  };

  callSendAPI(messageData);
}

function verifyRequestSignature(req, res, buf) {
  var signature = req.headers["x-hub-signature"];

  if (!signature) {
    // For testing, let's log an error. In production, you should throw an
    // error.
    console.error("Couldn't validate the signature.");
  } else {
    var elements = signature.split('=');
    var method = elements[0];
    var signatureHash = elements[1];

    var expectedHash = crypto.createHmac('sha1', APP_SECRET)
        .update(buf)
        .digest('hex');

    if (signatureHash != expectedHash) {
      throw new Error("Couldn't validate the request signature.");
    }
  }
}

const bodyParser = require('body-parser')
const express = require('express');
const https = require('https');
const request = require('request');
const crypto = require('crypto');

var app = express();
app.set('port', process.env.PORT || 5000);
app.use(bodyParser.json({ verify: verifyRequestSignature }));
app.use(express.static('public'));

const VALIDATION_TOKEN = process.env.VALIDATION_TOKEN;
const PAGE_ACCESS_TOKEN = process.env.PAGE_ACCESS_TOKEN;
const APP_SECRET = process.env.APP_SECRET;
const GIPHY_API_TOKEN = "dc6zaTOxFJmzC";

if (!VALIDATION_TOKEN) {
  console.error("VALIDATION_TOKEN missing");
  process.exit(1);
}

app.get("/", function(req, res){
  res.send("hello");
})

// Routes
app.get('/webhook', function(req, res) {
  if (req.query['hub.verify_token'] === VALIDATION_TOKEN) {
    console.log("Validating webhook");
    res.status(200).send(req.query['hub.challenge']);
  } else {
    console.error("Failed validation. Make sure the validation tokens match.");
    res.sendStatus(403);
  }
});

app.post('/webhook', function (req, res) {
//  console.log(req)
  var data = req.body;
  console.log(data);

  if (data.object == 'page') {
    data.entry.forEach(function (pageEntry) {
      pageEntry.messaging.forEach(function (msg) {
        if (isTextMessage(msg)) {
          handleTextMessage(msg)
          // ignore others for now
          // TODO: do not ignore
        }
      });
    });
  }
  res.sendStatus(200);
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});
<|endoftext|>


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

console.log("=====  hi there============");
app.get('/',function(req,res) {
  res.send("Hello World");
});

app.listen(4000);
<commit_msg>test commit to check jenkins2<commit_after>var express = require('express');
var app = express();

console.log("=====  asdhi there============");
app.get('/',function(req,res) {
  res.send("Hello World");
});

app.listen(4000);
<|endoftext|>


<commit_before>var url = require('url');
var util = require('util');
var path = require('path');
var http = require('http');
var fs = require('fs');
var bower = require('bower');
var StaticServer = require('node-static').Server;
var pkg = require('./package');

var loaderTemplate = path.join(__dirname, '..', 'templates', 'debug-loader.js');
var loaderParts = fs.readFileSync(loaderTemplate, 'utf8').split('{{scripts}}');

function getMainPath(config) {
  var main = config.main;
  if (util.isArray(main)) {
    main = main.reduce(function(prev, cur) {return (/\.js$/).test(cur) ? cur : prev;}, null);
  }
  if (!main) {
    throw new Error('No main JavaScript found in app component.json');
  }
  main = path.normalize(main);
  if ((/^[\/\.]/).test(main)) {
    throw new Error('The main JavaScript must be a relative path witin the app directory');
  }
  return main;
}

function getScriptPath(dir, main) {
  var script = bower.config.directory + '/' + config.name + '/' + getMainPath(config);
  if (script.substring(script.length - 3) !== '.js') {
    // TODO: unhack this
    script = script + '.js';
  }
  return script;
}

var headers = {
  'Content-Type': 'application/javascript'
};

exports.createDebugServer = function(config) {
  var dir = config.dir;
  var appConfig;
  try {
    appConfig = require(path.join(dir, bower.config.json));
  } catch (error) {
    console.error('Not a valid package (no %s found in %s)', bower.config.json, dir);
    process.exit(1);
  }
  var main = getMainPath(appConfig);
  var staticServer = new StaticServer(dir);
  return function(request, response) {
    var pathname = url.parse(request.url).pathname;
    // consume leading slash
    pathname = pathname.substring(1);
    if (pathname.indexOf(main) === 0) {
      pkg.getComponents(dir)
          .then(function(components) {
            components.pop();
            var scripts = components.map(getScriptPath);
            scripts.push(main);
            var script = pathname.substr(main.length + 1);
            if (script) {
              staticServer.serveFile(script, 200, headers, request, response)
                  .on('error', function(error) {
                    console.log(error);
                    response.writeHead(409, {'Content-Type': 'text/plain'});
                    response.end('Not found: ' + script + '\n');
                  });
            } else {
              var content = loaderParts.join(JSON.stringify(scripts));
              response.writeHead(200, headers);
              response.end(content);
            }
          })
          .fail(function(error) {
            util.puts(error);
            response.writeHead(500, {'Content-Type': 'text/plain'});
            response.end('Server error\n');
          });
    } else {
      staticServer.serve(request, response, function(error, result) {
        if (error) {
          response.writeHead(error.status, error.headers);
          response.end(error.message);
        }
      });
    }
  };
};

<commit_msg>Error handling<commit_after>var url = require('url');
var util = require('util');
var path = require('path');
var http = require('http');
var fs = require('fs');
var bower = require('bower');
var StaticServer = require('node-static').Server;
var pkg = require('./package');

var loaderTemplate = path.join(__dirname, '..', 'templates', 'debug-loader.js');
var loaderParts = fs.readFileSync(loaderTemplate, 'utf8').split('{{scripts}}');

function getMainPath(config) {
  var main = config.main;
  if (util.isArray(main)) {
    main = main.reduce(function(prev, cur) {return (/\.js$/).test(cur) ? cur : prev;}, null);
  }
  if (!main) {
    throw new Error('No main JavaScript found in app component.json');
  }
  main = path.normalize(main);
  if ((/^[\/\.]/).test(main)) {
    throw new Error('The main JavaScript must be a relative path witin the app directory');
  }
  return main;
}

function getScriptPath(config) {
  var script = bower.config.directory + '/' + config.name + '/' + getMainPath(config);
  if (script.substring(script.length - 3) !== '.js') {
    // TODO: unhack this
    script = script + '.js';
  }
  return script;
}

var headers = {
  'Content-Type': 'application/javascript'
};

exports.createDebugServer = function(config) {
  var dir = config.dir;
  var appConfig;
  try {
    appConfig = require(path.join(dir, bower.config.json));
  } catch (error) {
    console.error('Not a valid package (no %s found in %s)', bower.config.json, dir);
    process.exit(1);
  }
  var main = getMainPath(appConfig);
  var staticServer = new StaticServer(dir);
  return function(request, response) {
    var pathname = url.parse(request.url).pathname;
    // consume leading slash
    pathname = pathname.substring(1);
    if (pathname.indexOf(main) === 0) {
      pkg.getComponents(dir)
          .then(function(components) {
            components.pop();
            var scripts = components.map(getScriptPath);
            scripts.push(main);
            var script = pathname.substr(main.length + 1);
            if (script) {
              staticServer.serveFile(script, 200, headers, request, response)
                  .on('error', function(error) {
                    response.writeHead(404, {'Content-Type': 'text/plain'});
                    response.end('Not found: ' + script + '\n');
                  });
            } else {
              var content = loaderParts.join(JSON.stringify(scripts));
              response.writeHead(200, headers);
              response.end(content);
            }
          })
          .fail(function(error) {
            util.puts(error.stack);
            response.writeHead(500, {'Content-Type': 'text/plain'});
            response.end('Server error\n');
          });
    } else {
      staticServer.serve(request, response, function(error, result) {
        if (error) {
          response.writeHead(error.status, error.headers);
          response.end(error.message);
        }
      });
    }
  };
};

<|endoftext|>


<commit_before>'use babel';

import { Emitter } from 'event-kit';
import path from "path";
import fs from 'fs';
import socket from "socket.io";
import CollabyStatusView from './collaby-status-view';
import { CompositeDisposable } from 'atom';
import Helper from './helpers';

export default class CollabyServer {

	constructor(options) {
		this.serverData = {
			clients: 0
		};

		this.emitter = new Emitter();
		this.subscriptions = new CompositeDisposable();

		// Create status view
    this.collabyStatusView = new CollabyStatusView("icon-radio-tower", "0");

		if(global.collaby.statusBar) {
			this.collabyStatusTile = global.collaby.statusBar.addRightTile({item: this.collabyStatusView, priority: -1});
			this.collabyStatusView.value.textContent = this.serverData.clients;
			this.subscriptions.add(atom.tooltips.add(this.collabyStatusView.element, {title: `${this.serverData.clients} clients on collaby server`}));
		}

		console.log("new server created");
		atom.notifications.addSuccess("Started a new collaby server for this project!");
	}

	listen(port) {
		try {
			this.socket = socket.listen(port);
      this.handleEvents();
      atom.notifications.addInfo("Server listens on port " + port + " now!");
      return(this.socket);
		}
    catch(e) {
			atom.notifications.addFatalError("Server cannot listen on port " + port + "!", {detail: e.name + " " + e.message, stack: e.stack, dismissable: true});
		}
	}

	updateStatusBar() {
		this.collabyStatusView.value.textContent = this.serverData.clients;
		this.subscriptions.add(atom.tooltips.add(this.collabyStatusView.element, {title: `${this.serverData.clients} clients on collaby server`}));
	}

	handleEvents() {
		this.socket.on('connection', (clientSocket) => {
			this.emitter.emit("connection", clientSocket);
			console.log("A user connected to server");
			atom.notifications.addInfo("A user connected!");
		  this.serverData.clients++;
			this.updateStatusBar();

			clientSocket.on('change', (data) => {
				clientSocket.broadcast.emit('change', data);
			});

			clientSocket.on('will-save', (data) => {
				clientSocket.broadcast.emit('will-save', data);
			});

			if (this.serverData.clients < 2) {return;}

			clientSocket.on('disconnect', () => {
				atom.notifications.addInfo("A user disconnected!");
			  this.serverData.clients--;
				this.updateStatusBar();
			});

			clientSocket.on('serverFilesObject', () => {
				let serverFilesObject = this.getFilesObject();
				clientSocket.emit("serverFilesObject", serverFilesObject);
			});

			clientSocket.on('diffFiles', (diff) => {
				console.log(diff);
				clientSocket.emit('diffFilesContent', this.getDiffFiles(diff));
			});

		});

	}

	getFilesObject() {

		let files = {};

		for (let projectPath of atom.project.getPaths()) {

			let name = path.basename(projectPath);
			let project = Helper.recSingleScan(name, projectPath);

			files[name] = project;

		}

		return files;
	}

	getDiffFiles(diffs) {

		if (!diffs) return;

		let files = new Array();

		for (let key of Object.keys(diffs)) {
			//normalizing paths
			diffs[key].path = Helper.normalizeSeperators(path);
			diffs[key].relPath = Helper.normalizeSeperators(relPath);

			if (diffs[key].directory == false) {
				files.push({content: fs.readFileSync(diffs[key].path, "utf8"), relPath: diffs[key].relPath})
			} else {
				console.log(diffs[key].path + " is a directory. Scanning");
				Helper.recScanCb(diffs[key].path, ({file, filePath, stat, relPath}) => {
					console.log("got file " + file);
					files.push({content: fs.readFileSync(filePath, "utf8"), relPath: relPath});
				}, diffs[key].relPath);
			}
		}

		// anti crash protection (max files)
		if (files.length > atom.config.get("collaby.maxFiles")) {
			atom.notifications.addFatalError("Could not send files: too many files!", {
				detail: "A user wants to sync too many files (" + files.length + "). There are only " + atom.config.get("collaby.maxFiles") + " allowed. Sending only the first " + atom.config.get("collaby.maxFiles") + " now"
			});
			files = files.slice(0, atom.config.get("collaby.maxFiles"));
		}

		return files;

	}

	close() {
		try {
			this.socket.close(() => {
				if (this.collabyStatusTile) this.collabyStatusTile.destroy();
				this.subscriptions.dispose();
				atom.notifications.addSuccess('Collaby server successfully closed.');
			});
		} catch (e) {
			console.error(e);
		}

	}

	onConnection(cb) {
		return this.emitter.on('connection', cb);
	}

}
<commit_msg>Fixed normalizing paths on server<commit_after>'use babel';

import { Emitter } from 'event-kit';
import path from "path";
import fs from 'fs';
import socket from "socket.io";
import CollabyStatusView from './collaby-status-view';
import { CompositeDisposable } from 'atom';
import Helper from './helpers';

export default class CollabyServer {

	constructor(options) {
		this.serverData = {
			clients: 0
		};

		this.emitter = new Emitter();
		this.subscriptions = new CompositeDisposable();

		// Create status view
    this.collabyStatusView = new CollabyStatusView("icon-radio-tower", "0");

		if(global.collaby.statusBar) {
			this.collabyStatusTile = global.collaby.statusBar.addRightTile({item: this.collabyStatusView, priority: -1});
			this.collabyStatusView.value.textContent = this.serverData.clients;
			this.subscriptions.add(atom.tooltips.add(this.collabyStatusView.element, {title: `${this.serverData.clients} clients on collaby server`}));
		}

		console.log("new server created");
		atom.notifications.addSuccess("Started a new collaby server for this project!");
	}

	listen(port) {
		try {
			this.socket = socket.listen(port);
      this.handleEvents();
      atom.notifications.addInfo("Server listens on port " + port + " now!");
      return(this.socket);
		}
    catch(e) {
			atom.notifications.addFatalError("Server cannot listen on port " + port + "!", {detail: e.name + " " + e.message, stack: e.stack, dismissable: true});
		}
	}

	updateStatusBar() {
		this.collabyStatusView.value.textContent = this.serverData.clients;
		this.subscriptions.add(atom.tooltips.add(this.collabyStatusView.element, {title: `${this.serverData.clients} clients on collaby server`}));
	}

	handleEvents() {
		this.socket.on('connection', (clientSocket) => {
			this.emitter.emit("connection", clientSocket);
			console.log("A user connected to server");
			atom.notifications.addInfo("A user connected!");
		  this.serverData.clients++;
			this.updateStatusBar();

			clientSocket.on('change', (data) => {
				clientSocket.broadcast.emit('change', data);
			});

			clientSocket.on('will-save', (data) => {
				clientSocket.broadcast.emit('will-save', data);
			});

			if (this.serverData.clients < 2) {return;}

			clientSocket.on('disconnect', () => {
				atom.notifications.addInfo("A user disconnected!");
			  this.serverData.clients--;
				this.updateStatusBar();
			});

			clientSocket.on('serverFilesObject', () => {
				let serverFilesObject = this.getFilesObject();
				clientSocket.emit("serverFilesObject", serverFilesObject);
			});

			clientSocket.on('diffFiles', (diff) => {
				console.log(diff);
				clientSocket.emit('diffFilesContent', this.getDiffFiles(diff));
			});

		});

	}

	getFilesObject() {

		let files = {};

		for (let projectPath of atom.project.getPaths()) {

			let name = path.basename(projectPath);
			let project = Helper.recSingleScan(name, projectPath);

			files[name] = project;

		}

		return files;
	}

	getDiffFiles(diffs) {

		if (!diffs) return;

		let files = new Array();

		for (let key of Object.keys(diffs)) {
			//normalizing paths
			diffs[key].path = Helper.normalizeSeperators(diffs[key].path);
			diffs[key].relPath = Helper.normalizeSeperators(diffs[key].relPath);

			if (diffs[key].directory == false) {
				files.push({content: fs.readFileSync(diffs[key].path, "utf8"), relPath: diffs[key].relPath})
			} else {
				console.log(diffs[key].path + " is a directory. Scanning");
				Helper.recScanCb(diffs[key].path, ({file, filePath, stat, relPath}) => {
					console.log("got file " + file);
					files.push({content: fs.readFileSync(filePath, "utf8"), relPath: relPath});
				}, diffs[key].relPath);
			}
		}

		// anti crash protection (max files)
		if (files.length > atom.config.get("collaby.maxFiles")) {
			atom.notifications.addFatalError("Could not send files: too many files!", {
				detail: "A user wants to sync too many files (" + files.length + "). There are only " + atom.config.get("collaby.maxFiles") + " allowed. Sending only the first " + atom.config.get("collaby.maxFiles") + " now"
			});
			files = files.slice(0, atom.config.get("collaby.maxFiles"));
		}

		return files;

	}

	close() {
		try {
			this.socket.close(() => {
				if (this.collabyStatusTile) this.collabyStatusTile.destroy();
				this.subscriptions.dispose();
				atom.notifications.addSuccess('Collaby server successfully closed.');
			});
		} catch (e) {
			console.error(e);
		}

	}

	onConnection(cb) {
		return this.emitter.on('connection', cb);
	}

}
<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var beerbot = require('./alcobot');

var app = express();
var port = process.env.PORT || 3000;

// body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));

// test route
app.get('/', function (req, res) { res.status(200).send('Go away') });

// dicebot
app.post('/alco', alcobot);

// basic error handler
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(400).send(err.message);
});

app.listen(port, function () {
  console.log('ICQ bot listening on port ' + port);
});
<commit_msg>init alcobot<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var alcobot = require('./alcobot');

var app = express();
var port = process.env.PORT || 3000;

// body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));

// test route
app.get('/', function (req, res) { res.status(200).send('Go away') });

// dicebot
app.post('/alco', alcobot);

// basic error handler
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(400).send(err.message);
});

app.listen(port, function () {
  console.log('ICQ bot listening on port ' + port);
});
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var DIR_ROOT            = __dirname + '/..',

        path                = require('path'),

        join                = require('join-io'),
        mollify             = require('mollify'),
        restafary           = require('restafary'),
        socketFile          = require('socket-file'),
        readjson            = require('readjson'),

        HOME                = require('os-homedir')(),
        Edit                = require('../json/edit.json'),
        jshint              = readjson.sync.try(path.join(HOME, '.jshintrc')),

        Root,

        minifyFunc          = mollify({
            dir     : DIR_ROOT
        });

    if (!jshint)
        jshint = readjson.sync('../.jshintrc');

    module.exports          = function(options) {
        return serve.bind(null, options);
    };

    module.exports.listen   = function(socket, options) {
        var ret;

        if (!options)
            options = {};

        if (!options.prefix)
            options.prefix = '/edward';

        if (!options.root)
            options.root = '/';

        Root = options.root;

        ret = socketFile(socket, options);

        return ret;
    };

    function checkOption(isOption) {
        var is,
            type    = typeof isOption;

        switch(type) {
        case 'function':
            is = isOption();
            break;

        case 'undefined':
            is = true;
            break;

        default:
            is = isOption;
        }

        return is;
    }

    function copy(from, to) {
        Object.keys(from).forEach(function(name) {
            to[name] = from[name];
        });
    }

    function readEdit(callback) {
        var homePath = HOME + '/.edward.json';

        readjson(homePath, function(error, edit) {
            var data = {};

            copy(Edit, data);

            if (!error)
                copy(edit, data);
            else if (error.code !== 'ENOENT')
                error = Error('edward --config ' + homePath + ': ' + error.message);
            else
                error = null;

            callback(error, data);
        });
    }

    function serve(options, req, res, next) {
        var joinFunc, restafaryFunc, isJoin, isConfig, isEdit,
            isJsHint,
            o           = options || {},
            isMin       = checkOption(o.minify),
            isOnline    = checkOption(o.online),
            isDiff      = checkOption(o.diff),
            isZip       = checkOption(o.zip),

            url         = req.url,
            prefix      = o.prefix || '/edward',

            isEdward    = !url.indexOf(prefix),
            EDIT        = '/edit.json',
            JSHINT      = '/jshint.json',
            URL         = '/edward.js',
            CONFIG      = '/options.json',
            MODULES     = '/modules.json',
            PATH        = '/lib/client.js',

            isRestafary,

            sendFile    = function() {
                url = path.normalize(DIR_ROOT + url);
                res.sendFile(url);
            };

        if (!isEdward) {
            next();
        } else {
            url         = url.replace(prefix, '');

            isJoin      = !url.indexOf('/join');
            isJsHint    = url === JSHINT;
            isConfig    = url === CONFIG;
            isEdit      = url === EDIT;
            isRestafary = [
                '/api/v1/fs',
                '/restafary.js'
            ].some(function(item) {
                return !url.indexOf(item);
            });

            switch(url) {
            case URL:
                url = PATH;
                break;

            case MODULES:
                url = '/json' + url;
                break;
            }

            req.url = url;

             if (isEdit) {
                readEdit(function(error, data) {
                    if (error)
                        res.status(404)
                            .send(error.message);
                    else
                        res .type('json')
                            .send(data);
                });
            } else if (isConfig) {
                res .type('json')
                    .send({
                        diff: isDiff,
                        zip: isZip,
                        online: isOnline
                    });
            } else if (isJoin) {
                joinFunc = join({
                    dir     : DIR_ROOT,
                    minify  : isMin
                });

                joinFunc(req, res, next);
            } else if (isMin) {
                minifyFunc(req, res, sendFile);
            } else if (isRestafary) {
                restafaryFunc = restafary({
                    prefix: '/api/v1/fs',
                    root: Root
                });

                restafaryFunc(req, res, next);
            } else if (isJsHint) {
                res .type('json')
                    .send(jshint);
            } else {
                sendFile();
            }
        }
    }
})();
<commit_msg>fix(server) .jshintrc path<commit_after>(function() {
    'use strict';

    var DIR_ROOT            = __dirname + '/..',

        path                = require('path'),

        join                = require('join-io'),
        mollify             = require('mollify'),
        restafary           = require('restafary'),
        socketFile          = require('socket-file'),
        readjson            = require('readjson'),

        HOME                = require('os-homedir')(),
        Edit                = require('../json/edit.json'),
        jshint              = readjson.sync.try(path.join(HOME, '.jshintrc')),

        Root,

        minifyFunc          = mollify({
            dir     : DIR_ROOT
        });

    if (!jshint)
        jshint = readjson.sync(path.join(DIR_ROOT, '.jshintrc'));

    module.exports          = function(options) {
        return serve.bind(null, options);
    };

    module.exports.listen   = function(socket, options) {
        var ret;

        if (!options)
            options = {};

        if (!options.prefix)
            options.prefix = '/edward';

        if (!options.root)
            options.root = '/';

        Root = options.root;

        ret = socketFile(socket, options);

        return ret;
    };

    function checkOption(isOption) {
        var is,
            type    = typeof isOption;

        switch(type) {
        case 'function':
            is = isOption();
            break;

        case 'undefined':
            is = true;
            break;

        default:
            is = isOption;
        }

        return is;
    }

    function copy(from, to) {
        Object.keys(from).forEach(function(name) {
            to[name] = from[name];
        });
    }

    function readEdit(callback) {
        var homePath = HOME + '/.edward.json';

        readjson(homePath, function(error, edit) {
            var data = {};

            copy(Edit, data);

            if (!error)
                copy(edit, data);
            else if (error.code !== 'ENOENT')
                error = Error('edward --config ' + homePath + ': ' + error.message);
            else
                error = null;

            callback(error, data);
        });
    }

    function serve(options, req, res, next) {
        var joinFunc, restafaryFunc, isJoin, isConfig, isEdit,
            isJsHint,
            o           = options || {},
            isMin       = checkOption(o.minify),
            isOnline    = checkOption(o.online),
            isDiff      = checkOption(o.diff),
            isZip       = checkOption(o.zip),

            url         = req.url,
            prefix      = o.prefix || '/edward',

            isEdward    = !url.indexOf(prefix),
            EDIT        = '/edit.json',
            JSHINT      = '/jshint.json',
            URL         = '/edward.js',
            CONFIG      = '/options.json',
            MODULES     = '/modules.json',
            PATH        = '/lib/client.js',

            isRestafary,

            sendFile    = function() {
                url = path.normalize(DIR_ROOT + url);
                res.sendFile(url);
            };

        if (!isEdward) {
            next();
        } else {
            url         = url.replace(prefix, '');

            isJoin      = !url.indexOf('/join');
            isJsHint    = url === JSHINT;
            isConfig    = url === CONFIG;
            isEdit      = url === EDIT;
            isRestafary = [
                '/api/v1/fs',
                '/restafary.js'
            ].some(function(item) {
                return !url.indexOf(item);
            });

            switch(url) {
            case URL:
                url = PATH;
                break;

            case MODULES:
                url = '/json' + url;
                break;
            }

            req.url = url;

             if (isEdit) {
                readEdit(function(error, data) {
                    if (error)
                        res.status(404)
                            .send(error.message);
                    else
                        res .type('json')
                            .send(data);
                });
            } else if (isConfig) {
                res .type('json')
                    .send({
                        diff: isDiff,
                        zip: isZip,
                        online: isOnline
                    });
            } else if (isJoin) {
                joinFunc = join({
                    dir     : DIR_ROOT,
                    minify  : isMin
                });

                joinFunc(req, res, next);
            } else if (isMin) {
                minifyFunc(req, res, sendFile);
            } else if (isRestafary) {
                restafaryFunc = restafary({
                    prefix: '/api/v1/fs',
                    root: Root
                });

                restafaryFunc(req, res, next);
            } else if (isJsHint) {
                res .type('json')
                    .send(jshint);
            } else {
                sendFile();
            }
        }
    }
})();
<|endoftext|>


<commit_before>import './assets/css/style.css';

const title = document.createElement('h1');
title.textContent = 'Hello Poi!';
title.className = 'title';

const tip = document.createElement('div');
tip.textContent = 'Edit src/index.ts and save to reload.';
tip.className = 'tip';

const app = document.getElementById('app');

if (app) {
  app.appendChild(title);
  app.appendChild(tip);
}
<commit_msg>tweaks<commit_after>import './assets/css/style.css';

const title = document.createElement('h1');
title.textContent = 'Hello Poi!';
title.className = 'title';

const tip = document.createElement('div');
tip.textContent = 'Edit src/index.js and save to reload.';
tip.className = 'tip';

const app = document.getElementById('app');

if (app) {
  app.appendChild(title);
  app.appendChild(tip);
}
<|endoftext|>


<commit_before>var WS = require('ws').Server
var server = new WS({ port: 3000 })
var Device = require('ev3-js-device')
var devices = require('ev3-js-devices')
var fs = require('fs')

var sensors = getSensors()

var running = false
var sendInterval

server.on('connection', function (socket) {
  console.log('connected')
  if (!running) {
    running = true
    sendInterval = setInterval(readSensors, 150)
  }
  socket.on('close', function () {
    console.log('close')
    clearInterval(sendInterval)
    running = false
  })

  function readSensors () {
    for (var port in sensors) {
      socket.send(JSON.stringify({
        type: sensors[port].type,
        data: sensors[port].read('value0')
      }))
    }
  }
})

function getSensors () {
  return [1, 2, 3, 4].reduce(function (obj, port) {
    try {
      var path = devices(port)
      obj[port] = {
        type: fs.readFileSync(path + '/driver_name', 'utf-8').trim(),
        device: new Device(path)
      }
    } catch (e) {}
    return obj
  }, {})
}
<commit_msg>stringify response<commit_after>var WS = require('ws').Server
var server = new WS({ port: 3000 })
var Device = require('ev3-js-device')
var devices = require('ev3-js-devices')
var fs = require('fs')

var sensors = getSensors()

var running = false
var sendInterval

server.on('connection', function (socket) {
  console.log('connected')
  if (!running) {
    running = true
    sendInterval = setInterval(readSensors, 150)
  }
  socket.on('close', function () {
    console.log('close')
    clearInterval(sendInterval)
    running = false
  })

  function readSensors () {
    for (var port in sensors) {
      var data = sensors[port].read('value0')
      socket.send(JSON.stringify({
        type: sensors[port].type,
        data: data
      }))
    }
  }
})

function getSensors () {
  return [1, 2, 3, 4].reduce(function (obj, port) {
    try {
      var path = devices(port)
      obj[port] = {
        type: fs.readFileSync(path + '/driver_name', 'utf-8').trim(),
        device: new Device(path)
      }
    } catch (e) {}
    return obj
  }, {})
}
<|endoftext|>


<commit_before>import Phaser from 'phaser'
import Ship from '../sprites/Ship'
import Asteroid from '../sprites/Asteroid'
import Robot from '../sprites/Robot'
import Planet, { planets } from '../sprites/Planet'
import Coin from '../sprites/Coin'
export default class extends Phaser.State {
  init () {}
  preload () {}

  create () {
    //Setup physics
    game.physics.startSystem(Phaser.Physics.ARCADE);

    // Set up game input.
    game.cursors = game.input.keyboard.createCursorKeys()
    game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ])

    var worldWidth = 2000;
    var worldHeight = 2000;

    this.background = new Phaser.TileSprite(game, 0, 0, worldWidth, worldHeight, 'background')

    this.world.setBounds(0,0,worldWidth,worldHeight);
    this.player = new Ship({
      game: this,
      x: this.world.centerX,
      y: this.world.centerY,
      asset: 'ship'
    })
    this.player.body.collideWorldBounds = true;
    game.camera.follow(this.player);

    this.player.body.collideWorldBounds = true;
    this.camera.follow(this.player);

    this.game.add.existing(this.background)
    this.addPlanets()
    this.game.add.existing(this.player);

    this.fuelText = game.add.retroFont('knightHawks', 31, 25, Phaser.RetroFont.TEXT_SET2, 10, 1, 0)
    var fuelTextImage = game.add.image(5, 5, this.fuelText)
    fuelTextImage.tint = 0xFF7766
    fuelTextImage.fixedToCamera = true

    this.healthText = game.add.retroFont('knightHawks', 31, 25, Phaser.RetroFont.TEXT_SET2, 10, 1, 0)
    var healthTextImage = game.add.image(380, 5, this.healthText)
    healthTextImage.tint = 0x28bb35
    healthTextImage.fixedToCamera = true

    this.asteroids = game.add.physicsGroup();
    this.robots = game.add.physicsGroup();
    this.explosions = game.add.group();
    this.explosions.createMultiple(30, 'kaboom');
    this.explosions.forEach(this.setupExplosion, this);

    // Set up a weapon
    this.weapon = game.add.weapon(50, 'bullet')
    this.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;
    this.weapon.bulletSpeed = 700;
    this.weapon.fireRate = 100;
    this.weapon.trackSprite(this.player, 0, 0, true);

    this.CoinGroup = this.game.add.physicsGroup();

    // Audio
    this.laser1 = game.add.audio('laser1');
    this.laser2 = game.add.audio('laser2');
    this.explosion1 = game.add.audio('explosion1');
    this.coin1 = game.add.audio('coin1');
  }

  setupExplosion(explosion) {
    explosion.anchor.x = 0.5;
    explosion.anchor.y = 0.5;
    explosion.animations.add('kaboom');
  }

  processHandler (player, asteroids) {
    return true;
  }

  update() {
    this.addAsteroid();
    this.addRobot();

	  this.addCoin();

    if(game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
      console.log('b');
      this.weapon.fire();
      this.laser1.play();
    }

    if (game.physics.arcade.collide(this.player, this.asteroids, this.playerCollideAsteroid, null, this)) {
      console.log("Player got a coin!");
    }
    if (game.physics.arcade.overlap(this.player, this.CoinGroup, this.playerCollideCoin, null, this)) {
      console.log("Player got a coin!");
    }
    if (game.physics.arcade.collide(this.player.bullet, this.asteroids, this.bulletCollideAsteroidHandler, this.processHandler, this)) {
      console.log('Player shot an asteroid');
    }
    if (game.physics.arcade.collideGroupVsSelf(this.asteroids, this.asteroidCollideAsteroidHandler,  this.processHandler, this))
    {
      console.log('asteroid hit asteroid!');
    }
    if (game.physics.arcade.collideGroupVsSelf(this.robots, this.robotCollideRobot,  this.processHandler, this))
    {
      console.log('robot hit robot!');
    }
    game.physics.arcade.collide(this.player, this.robots, this.playerCollideRobot, this.processHandler, this)
    game.physics.arcade.collide(this.player.bullet, this.robots, this.playerBulletCollideRobot, this.processHandler, this)
  }

  playerCollideRobot(player, robot) {

  }
  robotCollideRobot(robot1, robot2) {

  }
  playerBulletCollideRobot(bullet, robot) {

  }

  asteroidCollideAsteroidHandler (asteroid1, asteroid2) {
    this.explosion1.play();
    var explosion = this.explosions.getFirstExists(false);
    explosion.reset((asteroid1.body.x + asteroid2.body.x) / 2,
      (asteroid1.body.y + asteroid2.body.y) / 2);
    asteroid1.destroy();
    asteroid2.destroy();
    explosion.play('kaboom', 30, false, true);
  }

  bulletCollideAsteroidHandler (bullet, asteroid) {
    this.explosion1.play();
    var explosion = this.explosions.getFirstExists(false);
    if (!explosion) return;
    explosion.reset(object.body.x, object.body.y);
    object.destroy();
    explosion.play('kaboom', 30, false, true);
  }

  playerCollideAsteroid (player, asteroid) {
    this.explosion1.play();
    this.player.health -= player.maxHealth/10;
    if (this.player.health <= 0) {
      //TODO:  Kill player and explode ship
    }

    var explosion = this.explosions.getFirstExists(false);
    explosion.reset(asteroid.body.x, asteroid.body.y);
    asteroid.destroy();
    explosion.play('kaboom', 30, false, true);
  }

  playerCollideCoin (player, coin) {
    //  If the ship collides with a coin it gets eaten :)
    this.coin1.play();
    coin.kill();
  }

  addPlanets() {
    const planetDensity = 0.000004
    const planetCount = this.world.width * this.world.height * planetDensity
    this.game.planets = []

    for (var i = 0; i < planetCount; i++) {
      var planet = new Planet({
        game: this,
        x: this.world.randomX,
        y: this.world.randomY,
        asset: Phaser.ArrayUtils.getRandomItem(planets)
      })
      this.game.planets.push(planet)
      this.game.add.existing(planet)
    }
  }

  render () {
    var x = 32
    var y = 32

    this.fuelText.text = 'fuel:' + Math.round(this.player.fuel / this.player.fuelMax * 100) + '%'
    this.healthText.text = 'shields:' + Math.round(this.player.health / this.player.maxHealth * 100) + '%'
  }

  addCoin() {
    var chanceOfCoin = 0.05;

    var coinRandom = Math.random();
    if (coinRandom < chanceOfCoin) {
        var xPos = this.world.width * Math.random();
        var yPos = this.world.width * Math.random();
        var newCoin = this.CoinGroup.create(xPos, yPos, 'coin');
        newCoin.width = 32;
        newCoin.height = 32;
        newCoin.animations.add('coin');
        newCoin.body.setCircle(10, 5, 5);//(radius,xoffset,yoffset);
        newCoin.play('coin', 10, true, false);
      }
    }

    addAsteroid() {
      var chanceOfAsteroid = 0.01;

      var asteroidRandom = Math.random();
      if (asteroidRandom < chanceOfAsteroid) {
        var newPosition = this.getPositionAlongEdge(asteroidRandom, chanceOfAsteroid);
        var newAsteroid = new Asteroid({ game: this, x: newPosition.x, y: newPosition.y, asset: 'asteroid' });
        this.asteroids.add(newAsteroid);
      }
    }

    addRobot() {
      var chanceOfRobot = 0.1;

      var robotRandom = Math.random();
      if (robotRandom < chanceOfRobot) {
        var newPosition = this.getPositionAlongEdge(robotRandom, chanceOfRobot);
        var newRobot = new Robot({ game: this, x: newPosition.x, y: newPosition.y, asset: 'robot' });
        this.robots.add(newRobot);
      }
    }

    getPositionAlongEdge(randomSeed, seedRange) {
      var xPos, yPos;
      if (randomSeed <= seedRange / 4)
      {
        xPos = this.world.width * Math.random();
        yPos = 0;
      }
      else if (randomSeed <= seedRange / 2) {
        xPos = this.world.width * Math.random();
        yPos = this.world.height-1;
      }
      else if (randomSeed <= (seedRange*3) /4 ) {
        xPos = 0;
        yPos = this.world.height * Math.random();
      }
      else {
        xPos = this.world.width-1;
        yPos = this.world.height * Math.random();
      }
      return {x:xPos, y:yPos};
    }
}
<commit_msg>Further cleaned up game.js, added robot/asteroid collisions<commit_after>import Phaser from 'phaser'
import Ship from '../sprites/Ship'
import Asteroid from '../sprites/Asteroid'
import Robot from '../sprites/Robot'
import Planet, { planets } from '../sprites/Planet'
import Coin from '../sprites/Coin'
export default class extends Phaser.State {
  init () {}
  preload () {}

  create () {
    //Setup physics
    game.physics.startSystem(Phaser.Physics.ARCADE);

    // Set up game input.
    game.cursors = game.input.keyboard.createCursorKeys()
    game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ])

    var worldWidth = 2000;
    var worldHeight = 2000;

    this.background = new Phaser.TileSprite(game, 0, 0, worldWidth, worldHeight, 'background')

    this.world.setBounds(0,0,worldWidth,worldHeight);
    this.player = new Ship({
      game: this,
      x: this.world.centerX,
      y: this.world.centerY,
      asset: 'ship'
    })
    this.player.body.collideWorldBounds = true;
    game.camera.follow(this.player);

    this.player.body.collideWorldBounds = true;
    this.camera.follow(this.player);

    this.game.add.existing(this.background)
    this.addPlanets()
    this.game.add.existing(this.player);

    this.fuelText = game.add.retroFont('knightHawks', 31, 25, Phaser.RetroFont.TEXT_SET2, 10, 1, 0)
    var fuelTextImage = game.add.image(5, 5, this.fuelText)
    fuelTextImage.tint = 0xFF7766
    fuelTextImage.fixedToCamera = true

    this.healthText = game.add.retroFont('knightHawks', 31, 25, Phaser.RetroFont.TEXT_SET2, 10, 1, 0)
    var healthTextImage = game.add.image(380, 5, this.healthText)
    healthTextImage.tint = 0x28bb35
    healthTextImage.fixedToCamera = true

    this.asteroids = game.add.physicsGroup();
    this.robots = game.add.physicsGroup();
    this.explosions = game.add.group();
    this.explosions.createMultiple(30, 'kaboom');
    this.explosions.forEach(this.setupExplosion, this);

    // Set up a weapon
    this.weapon = game.add.weapon(50, 'bullet')
    this.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;
    this.weapon.bulletSpeed = 700;
    this.weapon.fireRate = 100;
    this.weapon.trackSprite(this.player, 0, 0, true);

    this.CoinGroup = this.game.add.physicsGroup();

    // Audio
    this.laser1 = game.add.audio('laser1');
    this.laser2 = game.add.audio('laser2');
    this.explosion1 = game.add.audio('explosion1');
    this.coin1 = game.add.audio('coin1');
  }

  setupExplosion(explosion) {
    explosion.anchor.x = 0.5;
    explosion.anchor.y = 0.5;
    explosion.animations.add('kaboom');
  }

  update() {
    this.addAsteroid();
    this.addRobot();

	  this.addCoin();

    if(game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
      console.log('b');
      this.weapon.fire();
      this.laser1.play();
    }
    //Coin collection
    game.physics.arcade.overlap(this.player, this.CoinGroup, this.playerCollideCoin, null, this);

    //Player collisions
    game.physics.arcade.collide(this.player, this.asteroids, this.playerCollideAsteroid, null, this);
    game.physics.arcade.collide(this.player, this.robots, this.playerCollideRobot, this.processHandler, this);

    //Bullets
    game.physics.arcade.collide(this.player.bullet, this.asteroids, this.bulletCollideAsteroidHandler, this.processHandler, this);
    game.physics.arcade.collide(this.player.bullet, this.robots, this.playerBulletCollideRobot, this.processHandler, this);

    //Self-collisions
    game.physics.arcade.collideGroupVsSelf(this.asteroids, this.asteroidCollideOther,  this.processHandler, this);
    game.physics.arcade.collideGroupVsSelf(this.robots, this.robotCollideRobot,  this.processHandler, this);

    //Robot-collisions
    game.physics.arcade.collide(this.robots, this.asteroids, this.asteroidCollideOther, this.processHandler, this);
  }

  playerCollideRobot(player, robot) {

  }
  robotCollideRobot(robot1, robot2) {

  }
  playerBulletCollideRobot(bullet, robot) {

  }

  asteroidCollideOther (asteroid1, other) {
    this.explosion1.play();
    var explosion = this.explosions.getFirstExists(false);
    explosion.reset((asteroid1.body.x + other.body.x) / 2,
      (asteroid1.body.y + other.body.y) / 2);
    asteroid1.destroy();
    other.destroy();
    explosion.play('kaboom', 30, false, true);
  }

  bulletCollideAsteroidHandler (bullet, asteroid) {
    this.explosion1.play();
    var explosion = this.explosions.getFirstExists(false);
    if (!explosion) return;
    explosion.reset(object.body.x, object.body.y);
    object.destroy();
    explosion.play('kaboom', 30, false, true);
  }

  playerCollideAsteroid (player, asteroid) {
    this.explosion1.play();
    this.player.health -= player.maxHealth/10;
    if (this.player.health <= 0) {
      //TODO:  Kill player and explode ship
    }

    var explosion = this.explosions.getFirstExists(false);
    explosion.reset(asteroid.body.x, asteroid.body.y);
    asteroid.destroy();
    explosion.play('kaboom', 30, false, true);
  }

  playerCollideCoin (player, coin) {
    //  If the ship collides with a coin it gets eaten :)
    this.coin1.play();
    coin.kill();
  }

  addPlanets() {
    const planetDensity = 0.000004
    const planetCount = this.world.width * this.world.height * planetDensity
    this.game.planets = []

    for (var i = 0; i < planetCount; i++) {
      var planet = new Planet({
        game: this,
        x: this.world.randomX,
        y: this.world.randomY,
        asset: Phaser.ArrayUtils.getRandomItem(planets)
      })
      this.game.planets.push(planet)
      this.game.add.existing(planet)
    }
  }

  render () {
    var x = 32
    var y = 32

    this.fuelText.text = 'fuel:' + Math.round(this.player.fuel / this.player.fuelMax * 100) + '%'
    this.healthText.text = 'shields:' + Math.round(this.player.health / this.player.maxHealth * 100) + '%'
  }

  addCoin() {
    var chanceOfCoin = 0.05;

    var coinRandom = Math.random();
    if (coinRandom < chanceOfCoin) {
        var xPos = this.world.width * Math.random();
        var yPos = this.world.width * Math.random();
        var newCoin = this.CoinGroup.create(xPos, yPos, 'coin');
        newCoin.width = 32;
        newCoin.height = 32;
        newCoin.animations.add('coin');
        newCoin.body.setCircle(10, 5, 5);//(radius,xoffset,yoffset);
        newCoin.play('coin', 10, true, false);
      }
    }

    addAsteroid() {
      var chanceOfAsteroid = 0.01;

      var asteroidRandom = Math.random();
      if (asteroidRandom < chanceOfAsteroid) {
        var newPosition = this.getPositionAlongEdge(asteroidRandom, chanceOfAsteroid);
        var newAsteroid = new Asteroid({ game: this, x: newPosition.x, y: newPosition.y, asset: 'asteroid' });
        this.asteroids.add(newAsteroid);
      }
    }

    addRobot() {
      var chanceOfRobot = 0.1;

      var robotRandom = Math.random();
      if (robotRandom < chanceOfRobot) {
        var newPosition = this.getPositionAlongEdge(robotRandom, chanceOfRobot);
        var newRobot = new Robot({ game: this, x: newPosition.x, y: newPosition.y, asset: 'robot' });
        this.robots.add(newRobot);
      }
    }

    getPositionAlongEdge(randomSeed, seedRange) {
      var xPos, yPos;
      if (randomSeed <= seedRange / 4)
      {
        xPos = this.world.width * Math.random();
        yPos = 0;
      }
      else if (randomSeed <= seedRange / 2) {
        xPos = this.world.width * Math.random();
        yPos = this.world.height-1;
      }
      else if (randomSeed <= (seedRange*3) /4 ) {
        xPos = 0;
        yPos = this.world.height * Math.random();
      }
      else {
        xPos = this.world.width-1;
        yPos = this.world.height * Math.random();
      }
      return {x:xPos, y:yPos};
    }

  processHandler (player, asteroids) {
    return true;
  }
}
<|endoftext|>


<commit_before>var Log = require('./logger'),
  logger = new Log(global.logLevel),
  http = require("http"),
  url = require("url"),
  path = require("path"),
  fs = require("fs"),
  qs = require("querystring"),
  utils = require("./utils"),
  config = require('../lib/config'),
  exec = require('child_process').exec,
  chalk = require('chalk');

var mimeTypes = {
  "html": "text/html",
  "json": "text/json",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "png": "image/png",
  "js": "text/javascript",
  "css": "text/css"
};

function getTestBrowserInfo(worker) {
  var info = worker.string;
  if(config.multipleTest) {
    info += ", " + worker.test_path
  }
  return info;
}

exports.Server = function Server(bsClient, workers) {

  function handleFile(filename, request, response) {
    var url_parts = url.parse(request.url, true);
    var query = url_parts.query;

    if (query._worker_key && workers[query._worker_key]) {
      worker = workers[query._worker_key] || {};
      worker.acknowledged = true;
      logger.debug("[%s] Acknowledged", getTestBrowserInfo(worker));
    }

    fs.exists(filename, function(exists) {
      if (!exists) {
        response.writeHead(404, {
          "Content-Type": "text/plain"
        });
        response.write("404 Not Found\n");
        response.end();
        return;
      }

      if (fs.lstatSync(filename).isDirectory()) {
        filename = filename + (filename.lastIndexOf('/') == filename.length - 1 ? "" : "/") + "index.html";
      }

      fs.readFile(filename, {encoding: 'utf8'}, function(err, file) {

        if (err) {
          response.writeHead(500, {
            "Content-Type": "text/plain"
          });
          response.write(err + "\n");
          response.end();
          return;
        }

        var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
        response.writeHead(200, {
          "Content-Type": mimeType + "; charset=utf-8",
        });

        scripts = [
          'json2.js',
          'browserstack.js',
        ];

        framework_scripts = {
          'qunit': ['qunit-plugin.js'],
          'jasmine': ['jasmine-jsreporter.js', 'jasmine-plugin.js'],
          'mocha': ['mocha-plugin.js']
        };

        if (mimeType === 'text/html') {
          var matcher = /(.*)<\/head>/;
          var patch = "$1";
          scripts.forEach(function(script) {
            patch += "\n";
          });

          // adding framework scripts
          if (config['test_framework'] && config['test_framework'] == "jasmine") {
            framework_scripts['jasmine'].forEach(function(script) {
              patch += "\n";
            });
            patch += "\n";
          } else if (config['test_framework'] && config['test_framework'] == "mocha") {
            framework_scripts['mocha'].forEach(function(script) {
              patch += "\n";
            });
            patch += "\n";
          } else {
            framework_scripts['qunit'].forEach(function(script) {
              patch += "\n";
            });
          }
          patch += "";

          file = file.replace(matcher, patch);
        }

        response.write(file);
        response.end();
      });
    });
  }

  function parseBody(body) {
    // TODO: Have better implementation
    return JSON.parse(qs.parse(body).data.escapeSpecialChars());
  }

  function formatTraceback(details) {
    // looks like QUnit data
    if (details.testName) {
      var output = "'" + details.testName + "' failed";
      if (details.message) {
        output += ", " + details.message;
      }
      if (details.actual && details.expected) {
        output += "\n" + chalk.blue("Expected: ") + details.expected +
          "\n" + chalk.blue("  Actual: ") + details.actual;
      }
      if (details.source) {
        output += "\n" + chalk.blue("  Source: ") + "";
        output += details.source.split("\n").join("\n\t  ");
      }
      return output;
    }
    return details;
  }

  handlers = {
    "_progress": function progressHandler(uri, body, request, response) {
      var uuid = request.headers['x-worker-uuid'];
      var worker = workers[uuid] || {};
      query = "";
      try {
        query = parseBody(body);
      } catch(e) {
        logger.info("[%s] Exception in parsing log", worker.string);
        logger.info("[%s] Log: " + qs.parse(body).data, worker.string);
      }

      if (query.tracebacks) {
        query.tracebacks.forEach(function(traceback) {
          logger.info(chalk.red("[%s] Error:"), getTestBrowserInfo(worker), formatTraceback(traceback));
        });
      }
      response.end();
    },

    "_report": function reportHandler(uri, body, request, response) {
      query = null;
      try {
        query = parseBody(body);
      } catch (e) {}
      var uuid = request.headers['x-worker-uuid'];
      var worker = workers[uuid] || {};

      if (query === null) {
        logger.info("[%s] Null response from remote Browser", request.headers['x-browser-string']);
      } else {
        if (query.tracebacks && query.tracebacks.length > 0) {
          logger.info(chalk["red"]("[%s] Tracebacks:"), getTestBrowserInfo(worker));
          query.tracebacks.forEach(function(traceback) {
            logger.info(traceback);
          });
        }
        var color = query.failed ? "red" : "green";
        logger.info(chalk[color]("[%s] Completed in %d milliseconds. %d of %d passed, %d failed."), getTestBrowserInfo(worker), query.runtime, query.passed, query.total, query.failed);
        config.status += query.failed;
      }

      if (worker) {
        bsClient.takeScreenshot(worker.id, function(error, screenshot) {
          if (!error && screenshot.url) {
            logger.info('[%s] ' + chalk['yellow']('Screenshot') + ': %s', getTestBrowserInfo(worker), screenshot.url);
          }

          bsClient.terminateWorker(worker.id, function() {
            if (!workers[uuid]) {
              return;
            }

            logger.debug('[%s] Terminated', getTestBrowserInfo(worker));

            clearTimeout(workers[uuid].activityTimeout);
            clearTimeout(workers[uuid].testActivityTimeout);
            delete workers[uuid];

            if (utils.objectSize(workers) === 0) {
              var color = config.status > 0 ? "red" : "green";
              logger.info(chalk[color]("All tests done, failures: %d."), config.status);

              if (config.status > 0) {
                config.status = 1;
              }

              process.kill(process.pid, 'SIGTERM');
            }
          });
        });
      }

      response.end();
    },
    "_log": function logHandler(uri, body, request, response) {
      query = parseBody(body);
      logger.info('[' + request.headers['x-browser-string'] + '] ' + query);
      response.end();
    },
    "_patch": function patchHandler(uri, body, request, response) {
      handleFile(path.join(__dirname, uri), request, response);
    },
    "_default": function defaultHandler(uri, body, request, response) {
      handleFile(path.join(process.cwd(), uri), request, response);
    }
  };

  return http.createServer(function(request, response) {
    var uri = url.parse(request.url).pathname;
    var method = uri.split('/')[1];
    var filename;

    var body = '';

    request.on('data', function(data) {
      body += data;
    });
    request.on('end', function() {
      (handlers[method] || handlers._default)(uri, body, request, response);
    });
  });
};
<commit_msg>Fixes #66<commit_after>var Log = require('./logger'),
  logger = new Log(global.logLevel),
  http = require("http"),
  url = require("url"),
  path = require("path"),
  fs = require("fs"),
  qs = require("querystring"),
  utils = require("./utils"),
  config = require('../lib/config'),
  exec = require('child_process').exec,
  chalk = require('chalk');

var mimeTypes = {
  "html": "text/html",
  "json": "text/json",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "png": "image/png",
  "js": "text/javascript",
  "css": "text/css"
};

function getTestBrowserInfo(worker) {
  var info = worker.string;
  if(config.multipleTest) {
    info += ", " + worker.test_path
  }
  return info;
}

exports.Server = function Server(bsClient, workers) {

  function handleFile(filename, request, response) {
    var url_parts = url.parse(request.url, true);
    var query = url_parts.query;

    if (query._worker_key && workers[query._worker_key]) {
      worker = workers[query._worker_key] || {};
      worker.acknowledged = true;
      logger.debug("[%s] Acknowledged", getTestBrowserInfo(worker));
    }

    fs.exists(filename, function(exists) {
      if (!exists) {
        response.writeHead(404, {
          "Content-Type": "text/plain"
        });
        response.write("404 Not Found\n");
        response.end();
        return;
      }

      if (fs.lstatSync(filename).isDirectory()) {
        filename = filename + (filename.lastIndexOf('/') == filename.length - 1 ? "" : "/") + "index.html";
      }

      fs.readFile(filename, {encoding: 'utf8'}, function(err, file) {

        if (err) {
          response.writeHead(500, {
            "Content-Type": "text/plain"
          });
          response.write(err + "\n");
          response.end();
          return;
        }

        var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
        response.writeHead(200, {
          "Content-Type": mimeType + "; charset=utf-8",
        });

        scripts = [
          'json2.js',
          'browserstack.js',
        ];

        framework_scripts = {
          'qunit': ['qunit-plugin.js'],
          'jasmine': ['jasmine-jsreporter.js', 'jasmine-plugin.js'],
          'mocha': ['mocha-plugin.js']
        };

        var filePath = path.relative(process.cwd(), filename);
        var pathMatches;

        if (typeof config.test_path === 'object') {
          pathMatches = (config.test_path.indexOf(filePath) != -1);
        } else {
          pathMatches = (filePath == config.test_path);
        }
        if (pathMatches && mimeType === 'text/html') {
          var matcher = /(.*)<\/head>/;
          var patch = "$1";
          scripts.forEach(function(script) {
            patch += "\n";
          });

          // adding framework scripts
          if (config['test_framework'] && config['test_framework'] == "jasmine") {
            framework_scripts['jasmine'].forEach(function(script) {
              patch += "\n";
            });
            patch += "\n";
          } else if (config['test_framework'] && config['test_framework'] == "mocha") {
            framework_scripts['mocha'].forEach(function(script) {
              patch += "\n";
            });
            patch += "\n";
          } else {
            framework_scripts['qunit'].forEach(function(script) {
              patch += "\n";
            });
          }
          patch += "";

          file = file.replace(matcher, patch);
        }

        response.write(file);
        response.end();
      });
    });
  }

  function parseBody(body) {
    // TODO: Have better implementation
    return JSON.parse(qs.parse(body).data.escapeSpecialChars());
  }

  function formatTraceback(details) {
    // looks like QUnit data
    if (details.testName) {
      var output = "'" + details.testName + "' failed";
      if (details.message) {
        output += ", " + details.message;
      }
      if (details.actual && details.expected) {
        output += "\n" + chalk.blue("Expected: ") + details.expected +
          "\n" + chalk.blue("  Actual: ") + details.actual;
      }
      if (details.source) {
        output += "\n" + chalk.blue("  Source: ") + "";
        output += details.source.split("\n").join("\n\t  ");
      }
      return output;
    }
    return details;
  }

  handlers = {
    "_progress": function progressHandler(uri, body, request, response) {
      var uuid = request.headers['x-worker-uuid'];
      var worker = workers[uuid] || {};
      query = "";
      try {
        query = parseBody(body);
      } catch(e) {
        logger.info("[%s] Exception in parsing log", worker.string);
        logger.info("[%s] Log: " + qs.parse(body).data, worker.string);
      }

      if (query.tracebacks) {
        query.tracebacks.forEach(function(traceback) {
          logger.info(chalk.red("[%s] Error:"), getTestBrowserInfo(worker), formatTraceback(traceback));
        });
      }
      response.end();
    },

    "_report": function reportHandler(uri, body, request, response) {
      query = null;
      try {
        query = parseBody(body);
      } catch (e) {}
      var uuid = request.headers['x-worker-uuid'];
      var worker = workers[uuid] || {};

      if (query === null) {
        logger.info("[%s] Null response from remote Browser", request.headers['x-browser-string']);
      } else {
        if (query.tracebacks && query.tracebacks.length > 0) {
          logger.info(chalk["red"]("[%s] Tracebacks:"), getTestBrowserInfo(worker));
          query.tracebacks.forEach(function(traceback) {
            logger.info(traceback);
          });
        }
        var color = query.failed ? "red" : "green";
        logger.info(chalk[color]("[%s] Completed in %d milliseconds. %d of %d passed, %d failed."), getTestBrowserInfo(worker), query.runtime, query.passed, query.total, query.failed);
        config.status += query.failed;
      }

      if (worker) {
        bsClient.takeScreenshot(worker.id, function(error, screenshot) {
          if (!error && screenshot.url) {
            logger.info('[%s] ' + chalk['yellow']('Screenshot') + ': %s', getTestBrowserInfo(worker), screenshot.url);
          }

          bsClient.terminateWorker(worker.id, function() {
            if (!workers[uuid]) {
              return;
            }

            logger.debug('[%s] Terminated', getTestBrowserInfo(worker));

            clearTimeout(workers[uuid].activityTimeout);
            clearTimeout(workers[uuid].testActivityTimeout);
            delete workers[uuid];

            if (utils.objectSize(workers) === 0) {
              var color = config.status > 0 ? "red" : "green";
              logger.info(chalk[color]("All tests done, failures: %d."), config.status);

              if (config.status > 0) {
                config.status = 1;
              }

              process.kill(process.pid, 'SIGTERM');
            }
          });
        });
      }

      response.end();
    },
    "_log": function logHandler(uri, body, request, response) {
      query = parseBody(body);
      logger.info('[' + request.headers['x-browser-string'] + '] ' + query);
      response.end();
    },
    "_patch": function patchHandler(uri, body, request, response) {
      handleFile(path.join(__dirname, uri), request, response);
    },
    "_default": function defaultHandler(uri, body, request, response) {
      handleFile(path.join(process.cwd(), uri), request, response);
    }
  };

  return http.createServer(function(request, response) {
    var uri = url.parse(request.url).pathname;
    var method = uri.split('/')[1];
    var filename;

    var body = '';

    request.on('data', function(data) {
      body += data;
    });
    request.on('end', function() {
      (handlers[method] || handlers._default)(uri, body, request, response);
    });
  });
};
<|endoftext|>